Django switching, for a block of code, switch the language so translations are done in one language
django, gettext, internationalization, python, translation
Solution
simplest way to switch language is:
from django.utils.translation import activate
activate('en')
# do smthg
activate('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.
Problem
I have a django project that uses a worker process that sends emails to users. The worker processes listens to a rabbitmq server and gets all the details about the email to send, the template variables, the email address to send to etc. The email body is created with django templates and render_to_string. However I want to internationalize this. Some of our users are going to be using the website in English, some in other languages. They should get emails in their language. I have tried to i18n the email worker process (using django.utils.translations.ugettext/ugettext_lazy), so that the email subject and email body has _(...) or {% blocktrans %} resp. However since the email is rendered and sent in a different background worker process, the normal django language detection process doesn't seem to apply. There is no user session, no cookies or no http headers for it to look at. When sending the message to the rabbitmq server, I can store the language code But how do I tell django/gettext to use that language at a point. e.g. My function that sends email might look like this: ``` def send_email(details): lang = details['lang'] name = details['name'] email_address = details['email_address'] switch_gettext_to_this_language_what_goes_here(lang): # ????? email_subject = _("Welcome to $SITE") ``` What do I put in to switch django translations/gettext to a specific language code so that the `_()` will use that language code?