Django crispy-forms:没有国际化?

Django crispy-forms: No i18n?

在 Django 项目中,我使用 django.utils.translation 模块中的 ugettext 翻译字符串。例如,我翻译 models.py.

中的字符串

翻译工作完美,但不适用于 crispy-forms。为什么会这样,我该如何解决?

示例models.py

from django.utils.translation import ugettext as _

class CustomerUser(models.Model):
    LANGUAGE_CHOICES = (
        ('en', _('English')),
        ('de', _('German')),
    )

    name = models.CharField(null=False, blank=False, max_length=50)
    user = models.ForeignKey(User, blank=True, null=True)
    email = models.EmailField(blank=True, null=True)
    language = models.CharField(choices=LANGUAGE_CHOICES, default='en', max_length=2)
    customer = models.ForeignKey(Customer)
    changed_password = models.BooleanField(default=False)

    def __unicode__(self):
        return self.name

在视图中,我执行以下操作:

from django.utils import translation

translation.activate('de')

但脆皮形式没有翻译。 language 中的选项仍然呈现为 "German" 而不是 "Deutsch"。

尝试使用 ugettext_lazy

c.f。 This great answer on "When should I use ugettext_lazy?"

In definitions like forms or models you should use ugettext_lazy because the code of this definitions is only executed once (mostly on django's startup); ugettext_lazy translates the strings in a lazy fashion, which means, eg. every time you access the name of an attribute on a model the string will be newly translated-which makes totally sense because you might be looking at this model in different languages since django was started!

c.f。还有 crispy_forms test suite