0

Currently I have been learning Django and while reading, I have come across the below code block which I don't understand.

private = models.BooleanField(
        _('private'),
        default=False,
        help_text=_('theme is available ONLY for the site.'),
    )

The above line of code contains _('private') and I am not able to understand what it does. I know about using _ for translation-related stuff. Why attribute name not declared for _("private")?

I have tried to find the answer online but have been unable.

Thanks.

Alex Watt
  • 927
  • 5
  • 14
Moon
  • 4,014
  • 3
  • 30
  • 66
  • This is something I haven't come across. Have you tried running this piece of code and seeing the results? – Scratch'N'Purr Nov 09 '20 at 13:16
  • Are you using `django-translated-fields`? Why do you think this is related to `django-translated-fields`? – Uri Feb 09 '21 at 07:08

2 Answers2

3

_('private') sets the attribute verbose_name.

The leading underscore is the commonly used function alias for the one of the ugettext functions used by the internationalization (i18n) mechanics.

It means that when you have i18n running, the labels will be translated into the appropriate end-user language, if a translation is available.

Check this answer: https://stackoverflow.com/a/2964256/9361129

Wariored
  • 1,303
  • 14
  • 25
1

As you can see in the source code of Django, the constructor of a Field (which BooleanField inherits) takes verbose_name as first positional argument. So, your first argument (_('private')) will be affected to verbose_name.

However, to make your code clearer, I would recommend to pass it as a keyword argument:

private = models.BooleanField(
    verbose_name=_('private'),
    default=False,
    help_text=_('theme is available ONLY for the site.'),
)

Using keyword argument for verbose_name will make it clearer for you and people reading your code, especially since Django documentation does not give the order of positional arguments. Using positional argument forces readers to read Django source code to know what it is.

When you use keyword arguments, you can position your arguments as you like, so this code will work the same:

private = models.BooleanField(
    help_text=_('theme is available ONLY for the site.'),
    verbose_name=_('private'),
    default=False,
)
Antoine Pinsard
  • 33,148
  • 8
  • 67
  • 87