Joff
Joff

Reputation: 12187

Where to translate form field labels in Django?

I am working on getting my site translations up to speed and I have got .po/.mo files working with all of my {% trans %} tags in my template, but I cannot figure out how to get my forms to translate well. The fields do not show up in my .po files...

app/forms.py:

from django import forms
from django.utils.translation import ugettext_lazy as trans

class ContactForm(forms.Form):
    subject = forms.CharField(required=True, label=trans(u'Subject'))
    name = forms.CharField(required=True, label=trans(u'Name'))
    email = forms.EmailField(required=True, label=trans(u'Email'))
    content = forms.CharField(required=True, widget=forms.Textarea, label=trans(u'Content'))

I'm not sure what else I need to include here, please let me know if I need something else. I've tried to run

django-admin makemessages -l lang

but it doesn't populate with those fields

Upvotes: 5

Views: 3909

Answers (2)

You should use gettext_lazy() as _ or as so instead of tran which doesn't work as shown below. *_ is recommended:

from django.utils.translation import gettext_lazy as _

class ContactForm(forms.Form):                   # ↓ Here
    subject = forms.CharField(required=True, label=_('Subject'))
    ...

Or:

from django.utils.translation import gettext_lazy

class ContactForm(forms.Form):                   # ↓ ↓ Here ↓ ↓
    subject = forms.CharField(required=True, label=gettext_lazy('Subject'))
    ...

Upvotes: 1

Derek Kwok
Derek Kwok

Reputation: 13058

Unfortunately you can't use trans as a alias for marking strings that need to be translated. You must use either the original name of the function or _. E.g.

from django.utils.translation import ugettext_lazy as _
_('Subject') # this string will be marked for translation

or

from django.utils.translation import ugettext_lazy
ugettext_lazy('Subject') # this string will be marked for translation

Edit

Django uses xgettext behind the scenes for makemessages, and has a very specific list of keywords it picks up for translation:

--keyword=gettext_noop
--keyword=gettext_lazy
--keyword=ngettext_lazy:1,2
--keyword=ugettext_noop
--keyword=ugettext_lazy
--keyword=ungettext_lazy:1,2
--keyword=pgettext:1c,2
--keyword=npgettext:1c,2,3
--keyword=pgettext_lazy:1c,2
--keyword=npgettext_lazy:1c,2,3

Have a look at line 489 and onwards at https://github.com/django/django/blob/1.9/django/core/management/commands/makemessages.py

Upvotes: 4

Related Questions