首页 > 解决方案 > 如何以正确的方式在 Django 中翻译

问题描述

我想使用 django 以两种语言发送电子邮件。

在我的 settings.py 我有它如下:

LANGUAGE_CODE = 'en-us'

LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)

我的项目树如下:

在此处输入图像描述

发送邮件的代码如下:

to_email = [email, ]
from_email = 'no-reply@company.com'
to_cc_emails = download_documents_cc_emails
subject = _('The requested document')
html_content = render_to_string('email_templates/download_documents.html', {'name': name})

msg = EmailMultiAlternatives(subject, html_content, from_email, to_email, to_cc_emails)
msg.content_subtype = "html"  # Main content is now text/html
msg.attach_file(file_to_be_sent)
msg.send()

download_documents.html如下:

{% load i18n %}
<div>
    <div>{% trans "Dear" %} {{ name|capfirst }},</div>
    <div style="margin: 25px 0;">
        {% trans "The requested document is attached." %} <br />
    </div>
    <div>{% trans "Best regards" %}</div>
</div>

当我django-admin makemessages -l nl在语言环境文件夹中创建正确的标签时:

#: main/views.py:68
msgid "The requested document"
msgstr "Het aangevraagde document"

#: templates/email_templates/download_documents.html:3
msgid "Dear"
msgstr "Geachte"

#: templates/email_templates/download_documents.html:5
msgid "The requested document is attached."
msgstr "In bijlage vindt u het document."

#: templates/email_templates/download_documents.html:7
msgid "Best regards"
msgstr "Met vriendelijke groeten,"

但是当我收到电子邮件时,它没有被翻译。我收到英文的电子邮件。

知道我做错了什么吗?

标签: django

解决方案


您是否尝试在呈现电子邮件模板之前激活目标语言?

from django.utils import translation
translation.activate("nl")
...
render_to_string(...)

推荐阅读