Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the language in render_to_string helper?

From a save signal in Django I want to send an e-mail. The language of the email should be set based on the content being saved (it has a lang flag). How can I pass that language to Djangos render_to_string helper? I can only find language settings for RequestContexts, and there is no request or user available here.

Sincerely Björn

like image 574
Björn Lilja Avatar asked Dec 27 '10 14:12

Björn Lilja


1 Answers

Answer 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 (emphasis mine):

You can load a translation catalog, activate it and translate text to language of your choice, but remember to switch back to original language, as activating a translation catalog is done on per-thread basis and such change will affect code running in the same thread.

like image 161
dusan Avatar answered Sep 28 '22 01:09

dusan