Django切换,为一个代码块,切换语言,所以翻译是用一种语言完成的 [英] Django switching, for a block of code, switch the language so translations are done in one language

查看:134
本文介绍了Django切换,为一个代码块,切换语言,所以翻译是用一种语言完成的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django项目,它使用向用户发送电子邮件的工作进程。工作进程侦听一个rabbitmq服务器,并获取有关要发送的电子邮件的所有详细信息,模板变量,要发送到的电子邮件地址等。电子邮件正文使用django模板和 render_to_string



但是想要国际化这个。我们的一些用户将使用英文网站,其他一些用其他语言。他们应该用他们的语言发邮件。我试图在电子邮件工作者进程(使用django.utils.translations.ugettext / ugettext_lazy)i18n,以便电子邮件主体和电子邮件正文具有 _(...)或{%blocktrans%}分别。



但是,由于电子邮件是呈现并发送在不同的后台工作进程中,正常的 django语言检测过程似乎不适用。没有用户会话,没有Cookie或没有http标题来查看。将消息发送到rabbitmq服务器时,我可以存储语言代码



如何告诉django / gettext使用该语言一点。



例如发送电子邮件的功能可能如下所示:

  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 = _(欢迎来到$ SITE)

将django翻译/ gettext转换为特定的语言代码,以便 _()将使用该语言代码。

解决方案

最简单的切换语言的方式是:

  from django.utils.translation import activate 
激活('en')
#做smthg
激活('pl')
#用其他语言做某事
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?

解决方案

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.

这篇关于Django切换,为一个代码块,切换语言,所以翻译是用一种语言完成的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆