6

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.

shabda
  • 1,668
  • 1
  • 18
  • 28

2 Answers2

21

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'))
python273
  • 355
  • 3
  • 5
  • 3
    This answer is to be prefered to the answer with more upvotes imho. It does not play around with activating and deactivating translations which lead to troubles in my code and is an elegant solution to the problem. – Anna M. Jun 05 '20 at 10:26
10

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')
Amir Ali Akbari
  • 5,973
  • 5
  • 35
  • 47
  • 2
    if you had already set the locale previously ... does this wipe that out? Ive never seen this ... cool though – Joran Beasley Dec 05 '13 at 17:46
  • 1
    in Python 3 use: `gettext.translation('django', 'locale', ['de'], fallback=True).gettext('text')` it will always return unicode – Vlax May 25 '20 at 23:05