Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

python - Django switching, for a block of code, switch the language so translations are done in one language

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 translation
print(_("Hello"))  # Will print to Hello if default = 'en'

# Make a block where the language will be Danish
with 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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...