What is the best way to store language constants in django project?
For example, we know, that for translation we need to do:
from django.utils.translation import gettext_lazy as _
class MyThing(models.Model):
name = models.CharField(help_text=_('This is the help text'))
If we have a lot of variants, we can use dictionary like this:
from django.utils.translation import gettext_lazy as _
MYTRANSLATION = {
'term1':_('term1'),
'term2':_('term2'),
...
}
So, my question is, where to store dictionary with language constants… Directly in view, in model, in separate file in app folder, in root folder of project, etc… What is the best way? And where do you store your language consts?
I think it really depends. If you have a big public-facing site that you want to translate into N languages, then they aren’t constant and will require updates from dedicated translators whenever the content changes. For a project like that, gettext is wholly unsuitable because gettext is to hard for non-technical persons to use. The site will also require a recompile and redeploy to update the translations which are major dealbreakers if the content is to change often. gettext works for desktop applications (kind of, it is still a major pita for translators) but it does not for web sites.
Instead, use https://github.com/ojii/django-nani. Create a table to hold all translatable strings in your templates:
For each piece of text you need, add it as a row in I18NString. For example, you could add a row with the key “short-introduction-text” and add the English and German versions of the introduction texts there.
Then for each page load, load all translations for the current language:
Pass the trans dictionary to the template and render the translated strings: