Django 切换,对于一段代码,切换语言,以便翻译以一种语言完成

Django switching, for a block of code, switch the language so translations are done in one language(Django 切换,对于一段代码,切换语言,以便翻译以一种语言完成)

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

问题描述

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

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.

但是我想将其国际化.我们的一些用户将使用英语网站,一些用户使用其他语言.他们应该收到以他们的语言发送的电子邮件.我尝试过电子邮件工作进程(使用 django.utils.translations.ugettext/ugettext_lazy),以便电子邮件主题和电子邮件正文具有 _(...) 或 {% blocktrans %} resp.

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.

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

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

但是我如何告诉 django/gettext 在某一时刻使用该语言.

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")  

我应该输入什么来将 django 翻译/gettext 切换到特定的语言代码,以便 _() 将使用该语言代码?

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 切换,对于一段代码,切换语言,以便翻译以一种语言完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Django 切换,对于一段代码,切换语言,以便翻译以一种语言完成

基础教程推荐