3

Can someone tell me if there is a problem with the following approach in terms of the translation?

I am concerned that the verbose name becomes fixed at the point of database migration.

models.py

from django.utils.translation import gettext as _
class UserClient(models.Model):
    user             = models.OneToOneField(User,related_name='profile_client')
    phone_cell       = PhoneNumberField(verbose_name=_(u'Phone (Cell)'),null=True,blank=False)
    phone_home       = PhoneNumberField(verbose_name_(u'Phone (Home)'),null=True,blank=True)

If the above is problematic, is it better to implement the following?

forms.py

class ClientForm(forms.ModelForm):
    def __init__(self,*args,**kwargs):
        super(ClientForm,self).__init__(*args,**kwargs)
        self.fields['phone_cell'].label = _(u'Phone (Cell)')
        self.fields['phone_home'].label = _(u'Phone (Home)')
Nicholas Hamilton
  • 10,044
  • 6
  • 57
  • 88

1 Answers1

11

Your approach in models.py will work correctly provided you use the lazy version of gettext:

from django.utils.translation import ugettext_lazy as _

class UserClient(models.Model):
    phone_cell = PhoneNumberField(verbose_name=_('Phone (Cell)'), ...)
    ...

In fact, Django's very own models use the same technique for translation - have look at the AbstractUser class. You can be sure this approach will work properly.

Even though verbose_name exists in database migration, it's not used. Any code that relies on verbose_name will retrieve it from the model directly. For example, a ModelForm field's default label will use the model's verbose_name, and since the translation is lazy, the actual label will be translated when it is evaluated (e.g. rendering on a template).

Derek Kwok
  • 12,768
  • 6
  • 38
  • 58
  • Thanks, So should `ugettext_lazy` be used in preference to `gettext` all the time? Is there any advantage to using the non-lazy approach? – Nicholas Hamilton Feb 24 '16 at 07:23
  • 2
    @NicholasHamilton this answer sums it up pretty good: http://stackoverflow.com/a/4510998/189362 – Bjorn Feb 24 '16 at 07:24
  • @Bjorn thank you for the link! it's an excellent explanation of the difference between lazy vs non-lazy – Derek Kwok Feb 24 '16 at 07:25
  • That is helpful, I guess my question (which I know detracts from this thread) is, why use the non-lazy approach at all? Is there a performance cost associated with lazy loading? – Nicholas Hamilton Feb 24 '16 at 07:27
  • @NicholasHamilton it prevents circular references, the time of evaluation is just shifted so the performance is not a big thing imho – Daniel W. Apr 30 '20 at 20:03