7

I want to translate a django form. How do I translate the labels of the fields?

I tried field.label=ugettext_lazy(field.label), but the labels are not getting populated in django.po file

I may have gotten the concept of ugettext_lazy wrong, I think

In simple terms I want the field labels to be put into django.po file.

The other translations done using ugettext and {% trans %} tag are working well

I have been able to translate the fields based on a model by setting verbose_name but when I try that for a form field I get a TypeError

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129

5 Answers5

11

I will precise that :

from django.utils.translation import ugettext_lazy as _
...
first_name = forms.CharField(label=_(u'First name'))

It's likely to raise an error because forms cannot manage well a proxy object like _(u'First name'), and the result in rendering is a void form. I tested this on python2.x and django 1.3/1.4

The reason is due to the compiled .po messages initially created by different o.s. and libraries (it can depend by python,django,os. libraries versions). When you have this error you must re-create the localized messages.

mizar
  • 355
  • 4
  • 11
8
class ExampleForm(forms.Form):
    f1 = forms.CharField(label= ugettext_lazy('field label'))
Tommaso Barbugli
  • 11,781
  • 2
  • 42
  • 41
8
from django.utils.translation import ugettext_lazy as _
first_name = forms.CharField(label=_(u'First name'))
inlanger
  • 2,904
  • 4
  • 18
  • 30
0

As an alternative way, you can add script to your template.html

<script>
        labels = document.getElementsByTagName('label');
        for (var j = 0; j < labels.length; j++) {   
             if (labels[j].textContent == "Username:") labels[j].textContent =    "Логін   ";
             if (labels[j].textContent == "First name:") labels[j].textContent =  "Ім'я    ";
             if (labels[j].textContent == "Last name:") labels[j].textContent =   "Прізвище";
             if (labels[j].textContent == "Email address:") labels[j].textContent =   "Email адреса ";
             if (labels[j].textContent == "Password:") labels[j].textContent =        "Пароль            ";
             if (labels[j].textContent == "Confirm password:") labels[j].textContent =        "Підтвердити пароль";
             };
</script>
0

You should use gettext_lazy() and label in forms.CharField() as shown below:

from django.utils.translation import gettext_lazy as _

first_name = forms.CharField(label=_('First name'))
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129