This week, I’ll continue on the same theme of my previous “Django Friday Tips” post. Essentially, we will keep addressing small annoyances that can surface while developing your multilingual project.
The challenge for this article shows up when a given string from a package that is a dependency of your project is either:
- Not translated in the language you are targeting.
- Translated in a slightly different way than you desire.
As we are all aware, most packages use English by default, then the most popular ones often provide translations for languages that have more active users willing to contribute. But these efforts are laborious and can have differences for distinct regions, even if they use the same base language.
Contributing upstream, might not always be an option.
This means that to maintain the coherence of the interface of your project, you need to adapt these translations locally.
Handling the localization of the code in your repository in Django is obvious and well documented. Django collects the strings and adds the translation files to the locale path (per app or per project).
For the other packages, these strings and translations are located within their directory hierarchy, outside the reach of the makemessages
command. Django, on the other hand, goes through all these paths, searching for the first match.
With this in mind, the easiest and most straightforward way I was able to find to achieve this goal was:
Create a file in your project (in an app directory or in a common project directory), let’s call it locale_overrides.py
and put there the exact string from your dependency (Django or another) that you which to translate:
from django.utils.translation import gettext_lazy as _
locale_overrides = [
_("This could sound better."),
...
]
Then run manage.py makemessages
, translate the new lines in the .po
file as you wish, then finally compile your new translations with manage.py compilemessages
.
Since your new translations are found first, when your app is looking for them, they will be picked instead of the “original” ones.
For tiny adjustments, this method works great. When the amount of content starts growing too much, a new approach might be more appropriate, but that will be a topic for another time.