Django switching, for a block of code, switch the language so translations are done in one language
As @SteveMayne pointed out in comment (but it worth an answer), you can now use the context manager translation.override
(works with Django 1.6, didn't check with earlier versions):
from django.utils import translationprint(_("Hello")) # Will print to Hello if default = 'en'# Make a block where the language will be Danishwith translation.override('dk'): print(_("Hello")) # print "Hej"
It basically uses the same thing than @bitrut answer but it's built-in in Django, so it makes less dependencies...
You can force language in a nice way using context manager:
class force_lang: def __init__(self, new_lang): self.new_lang = new_lang self.old_lang = translation.get_language() def __enter__(self): translation.activate(self.new_lang) def __exit__(self, type, value, tb): translation.activate(self.old_lang)
Then you can use with
statement:
with force_lang('en'): ...
simplest way to switch language is:
from django.utils.translation import activateactivate('en')# do smthgactivate('pl')# do something in other language
be carefull with this as it is changing context for the rest of the execution of this process/thread.