0

In a Django project, I translate strings using ugettext from the django.utils.translation module. As an example, I translate strings in my models.py.

Translation works perfectly, but not with crispy-forms. Why is that and how can I fix this?

Example 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

In the view, I do the following:

from django.utils import translation

translation.activate('de')

but crispy forms aren't translated. The option from the language is still rendered as "German" instead of "Deutsch".

Daniel
  • 1,515
  • 3
  • 17
  • 30

1 Answers1

1

Try using 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. also The crispy_forms test suite

Community
  • 1
  • 1
Carlton Gibson
  • 7,278
  • 2
  • 36
  • 46