Django表单和i18n [英] Django form and i18n

查看:152
本文介绍了Django表单和i18n的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  agree_tos = forms.BooleanField(label = ugettext(我同意服务条款和隐私权政策))

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

  {{form.as_p}} 

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

解决方案

您应该使用 ugettext_lazy()

  from django.utils.translation import ugettext_lazy 

#...
agree_tos = forms.BooleanField(label = ugettext_lazy('我同意条款服务和隐私政策)

当您的Django应用程序启动时,模型和表单属性将被初始化。如果您使用 ugettext(),翻译将在初始化时设置一次,从不更改。 ugettext_lazy()通过在访问该值时翻译该字符串,而不是调用该函数来解决此问题。


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 ?

解决方案

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.'))

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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