How to set language in render_to_string helper?

From the save signal in Django, I want to send an email. The email language should be set based on the stored content (it has the lang flag). How to pass this language to Djangos helper render_to_string? I can only find the language settings for RequestContexts, and there is no request or user.

Regards Bjorn

+7
source share
4 answers

The answer is based on Django docs :

from django.template.loader import render_to_string from django.utils import translation (...) cur_language = translation.get_language() try: translation.activate(some_language) text = render_to_string('email-confirmation.html') finally: translation.activate(cur_language) 

And quoting the documentation (my emphasis):

You can download the translation catalog, activate it and translate the text into the language of your choice, but do not forget to return to the original language , since the activation of the translation catalog is carried out on one topic and such a change will affect the code running in the same thread.

+10
source

It seems I can use translation.activate (some_lang) before every message I send. I am not sure if this is effective or not.

I see that it is possible to send a Context instance to render_to_string. If I can somehow put the language setting in this context, it would be nice.

+1
source

you can pass custom dictionnary to render_to_string

 render_to_string(template_name, dictionary=None, context_instance=None) 

The default context variable for LANGUAGES (see django / middlewares / context_processors.py):

 context_extras['LANGUAGES'] = settings.LANGUAGES context_extras['LANGUAGE_CODE'] = translation.get_language() context_extras['LANGUAGE_BIDI'] = translation.get_language_bidi() 

therefore, it may be sufficient to set LANGUAGE_CODE:

 render_to_string('email-confirmation.html', {'LANGUAGE_CODE':'en'}) 

your template should look like this:

 {% load i18n %} {% trans "Welcome to our new webapp" %} 

Of course, you will be dealing with .po files, but you should be aware of this (unless you check this )

Hope this helps.

+1
source

From the documentation I found this way nicer:

To write more concise code, there is also the django.utils.translation.override () context manager, which stores the current language for input and restores it upon exit. In doing so, the above example becomes:

 from django.utils import translation def welcome_translated(language): with translation.override(language): return translation.ugettext('welcome') 
+1
source

All Articles