Django形式和i18n

mad*_*ulf 12 forms django internationalization

我有要以不同语言显示的表单:我使用label参数设置参数,并在标签上使用ugettext():

agreed_tos = forms.BooleanField(label=ugettext('I agree to the terms of service and to the privacy policy.'))
Run Code Online (Sandbox Code Playgroud)

但是当我在模板中渲染表单时,使用

{{form.as_p}}
Run Code Online (Sandbox Code Playgroud)

标签未翻译.有人有解决这个问题的方法吗?

Aym*_*ieh 20

你应该使用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.'))
Run Code Online (Sandbox Code Playgroud)

Django应用程序启动时初始化模型和表单属性.如果您使用ugettext(),翻译将在初始化时设置一次,永远不会更改.ugettext_lazy()通过在访问其值时转换字符串而不是在调用函数时解决此问题.