Search code examples
pythondjangodjango-formstranslationdjango-i18n

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


Solution

  • 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