问题描述
我有想要以不同语言显示的表单:我使用标签参数设置参数,并在标签上使用了 ugettext() :
I have forms that I want to display in different languages : I used the label parameter to set a parameter, and used ugettext() on the labels :
agreed_tos = forms.BooleanField(label=ugettext('I agree to the terms of service and to the privacy policy.'))
但是当我在模板中渲染表单时,使用
But when I am rendering the form in my template, using
{{form.as_p}}
标签未翻译.有人有解决这个问题的方法吗?
The labels are not translated. Does somebody have a solution for this problem ?
推荐答案
你应该使用 ugettext_lazy()
:
You should use ugettext_lazy()
:
from django.utils.translation import ugettext_lazy
# ...
agreed_tos = forms.BooleanField(label=ugettext_lazy('I agree to the terms of service and to the privacy policy.'))
模型和表单属性在您的 Django 应用程序启动时被初始化.如果您使用 ugettext()
,翻译将在初始化时设置一次并且永远不会改变.ugettext_lazy()
通过在访问字符串的值而不是调用函数时转换字符串来解决这个问题.
Model and form attributes are initialized when your Django application starts. If you use ugettext()
, the translation will be set once at initialization and never change. ugettext_lazy()
solves this problem by translating the string when its value is accessed rather than when the function is called.
这篇关于Django 表单和 i18n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!