I can get the translation in current locale using.
from django.utils.translation import ugettext as _
_("password")
However in my code (a form to be specific) I want to get the translation in a specific language. I want to be able to say.
ugettext_magic("de", "password")
I already have the strings translated in the languages I need.
Gettext works by, first, generating a template file with all the strings to be translated directly extracted from the source files, this template file is called a . pot file which stands for Portable Object Template.
gettext utilities are a set of tools that provides a framework to help other packages produce multi-lingual messages. The minimum version of the gettext utilities supported is 0.19.
October 28, 2020 · 16 min read. GNU gettext is a package that offers to programmers, translators and even users a well integrated set of tools that provide a framework within which other free packages may produce multi-lingual messages.
Context manager django.utils.translation.override activates a new language on enter and reactivates the previous active language on exit
from django.utils import translation
def get_translation_in(language, s):
with translation.override(language):
return translation.gettext(s)
print(get_translation_in('de', 'text'))
There is a workaround:
from django.utils import translation
from django.utils.translation import ugettext
def get_translation_in(string, locale):
translation.activate(locale)
val = ugettext(string)
translation.deactivate()
print get_translation_in('text', 'de')
Or simply:
gettext.translation('django', 'locale', ['de'], fallback=True).ugettext('text')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With