What does the underscore before the label value in Django forms mean

Viewed 376

I have came through the UserCreationForm in the django source code here. Here is the question, if you look at both password fields you will see an underscore before the label value, I wonder what's the purpose of it, because it's not written in the documentation since I searched for it.

class UserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
error_messages = {
    'password_mismatch': _('The two password fields didn’t match.'),
}
password1 = forms.CharField(
    label=_("Password"),
    strip=False,
    widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}),
    help_text=password_validation.password_validators_help_text_html(),
)
password2 = forms.CharField(
    label=_("Password confirmation"),
    widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}),
    strip=False,
    help_text=_("Enter the same password as before, for verification."),
)
1 Answers

This is an alias for the gettext_lazy(…) function [Django-doc]. Indeed, at line 19 [GitHub], we see:

from django.utils.translation import gettext, gettext_lazy as _

This will lazily translate the message. It means that if you render it in the template, the template will call str(…) on the lazy translation object. This will, depending on the activated language, provide a translated version of the label.

For more information about translations, see the Tranlation section of the Django documentation.

Related