NLStom
NLStom

Reputation: 41

Django models title = models.CharField(_('title'), max_length=100)

class PersonType(models.Model):
    """Person type model."""
    title = models.CharField(_('title'), max_length=100)
    slug = models.SlugField(_('slug'), unique=True)

I wonder what is _('titile') do here for title. And also what is _('slug') do for slug?

Upvotes: 1

Views: 2376

Answers (2)

hassanzadeh.sd
hassanzadeh.sd

Reputation: 3471

The _ is the name of a callable (function, callable object). It's usually used for the gettext function , for example in Django:

Django Ducumentation

you can use like this :

from django.utils.translation import gettext
equal output = gettext("Welcome to my site.")

Or like this

from django.utils.translation import gettext as _
output = _("Welcome to my site.")

both of them used for translation and yot can use this value in template like this :

<title>{% trans "Welcome to my site." %}</title>

# Will print "Welcome to my site." if the current language is English
# "Bienvenue sur mon site." in French
# "به سایت من خوش آمدید." in Iran

Upvotes: 1

brianpck
brianpck

Reputation: 8254

The first position argument of a Field subclass is the verbose_name of that field: see the __init__ constructor of Field:

class Field(RegisterLookupMixin):
   ...
   def __init__(self, verbose_name=None, name=None, ...)
       ...

The underscore _ is the alias by convention for ugettext_lazy: you probably will see the following line of code:

from django.utils.translation import ugettext_lazy as _

The Django docs offer a functionally equivalent snippet which uses a keyword argument rather than position args:

class MyThing(models.Model):
    name = models.CharField(verbose_name=_('This is the help text'))

This is a "lazy translation":

These functions store a lazy reference to the string – not the actual translation. The translation itself will be done when the string is used in a string context, such as in template rendering.

Upvotes: 2

Related Questions