Search code examples
pythondjangogettext

Purpose of ugettext inside of Models


In plenty of Django tuts, and everywhere online, people will create fields such as the below within a model class:

from django.db import models
from django.utils.translation import ugettext as _

class MyModel(models.Model)
    created = models.DateTimeField(
        _('Created'),
        auto_now_add=True
    )

I understand what ugettext is doing but I don't understand why it's being applied to, in this example, 'Created'. Why not just write:

created = models.DateTimeField(auto_now_add=True)

Furthermore, is 'Created' referring to something that's been defined somewhere? In this example, I don't see it existing in forms.py, nor is it passed through in views.py. So, whatever it is, it's existing solely within this model - or so I think.


Solution

  • I'm fairly sure it's just as simple as if you don't define that string, it'll get used to identify the field in a ModelForm. If you then use various languages on your site, that field wouldn't have a translated string associated with it.

    So you can define a form nice and easy, in forms.py;

    from django import forms
    
    from .models import MyModel
    
    
    class MyForm(forms.ModelForm):
        """
        MyForm is a nice a simple ModelForm using
        labels from MyModel.
        """
    
        class Meta:
            model = MyModel
            fields = ['created', ]
    
    # views.py
    from django.views.generic.edit import CreateView
    from django.core.urlresolvers import reverse_lazy
    
    from .forms import MyForm
    
    
    class MyObjCreate(CreateView):
        form_class = MyForm
    

    By adding that ugettext string, it would get pulled in to the message catalog which can then be translated. At least this makes sense from my experience of translations.

    Check out the docs, especially this about the class Meta of a model; https://docs.djangoproject.com/en/1.7/topics/i18n/translation/#model-verbose-names-values