I have recently introduced translation (i18n) to my django app.
It works fine for all templates and error messages. Not for forms unfortunately. It always falls back to English, even if the rest of the page is shown in German.
settings.py:
LANGUAGE_CODE = 'en'
USE_I18N = True
USE_L10N = True
forms.py:
from django import forms
from django.utils.translation import gettext as _
from django.conf import settings
from django.core.validators import DecimalValidator, MaxLengthValidator, EmailValidator, MinLengthValidator
class AccountCompanyNameForm(forms.ModelForm):
# adding some default validators
phone = forms.CharField(validators=[MinLengthValidator(10)],
error_messages={'invalid': _("Bitte geben Sie eine gültige Rufnummer an.")})
name = forms.CharField(label=_("Vorname Nachname"), validators=[MinLengthValidator(3)],
error_messages={'invalid': _("Bitte geben Sie Ihren Vor- und Nachnamen ein.")})
company = forms.CharField(label=_("Firma"), validators=[MinLengthValidator(3)],
error_messages={'invalid': _("Bitte geben Sie den Namen Ihrer Firma an.")})
birthdate = forms.DateField(label=_("Geburtsdatum"),
error_messages={'invalid': _("Bitte geben Sie das Datum im Format 01.01.1990 ein.")})
terms = forms.BooleanField()
Template code:
{% load i18n %}
{% load widget_tweaks %}
...
{% render_field form.company placeholder=form.company.label class+="form-control" %}
...
{{ form.company.label }}
Even the form.company.label is in English.
German translation is there and correct.
Any help is appreciated.
You are using gettext
which runs and translates everything when called, and your form body only runs once, when you start the server. However you'd want to have it translated everytime you get a request, with the current active language, which usually is set by a middleware.
Take a read here for more information.
For the quick fix, just turn gettext
there to gettext_lazy
and you are good to go.