shabda
shabda

Reputation: 1758

gettext for specific locales

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.

Upvotes: 8

Views: 4583

Answers (2)

python273
python273

Reputation: 397

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'))

Upvotes: 21

Amir Ali Akbari
Amir Ali Akbari

Reputation: 6396

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')

Upvotes: 10

Related Questions