17

I have a @property called name in my

class Person(models.Model):
    first_name = models.CharField("Given name", max_length=255)
    last_name = models.CharField("Family name ", max_length=255)

    @property
    def name(self):
        return "%s %s" % (self.first_name, self.last_name)

Is it easily possible to specify the verbose_name for this property?

SaeX
  • 17,240
  • 16
  • 77
  • 97
  • 1
    It is called `short_description` https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display – karthikr Mar 21 '14 at 16:18
  • Thanks @karthikr, but that only seems to work in the Admin using `admin.ModelAdmin`. I'm looking for similar behavior using `models.Model`. – SaeX Mar 21 '14 at 16:25
  • Out of curiosity, why would you need such a thing ? – karthikr Mar 21 '14 at 16:26
  • 1
    I was messing around with `django-tables2` and wanted to show a `@property` in a column. Apparently the fix there is to use `verbose_name` when defining the column. There might be other examples where this would be needed. – SaeX Mar 22 '14 at 15:38
  • 2
    Possible duplicate of [Django short description for property](http://stackoverflow.com/questions/7241000/django-short-description-for-property) – Fish Monitor Jun 20 '16 at 07:35
  • 1
    re fossilet's post. you should use my_property.fget.short_description = u'Property X'. thanks. – mark Jul 09 '18 at 22:22

2 Answers2

18

A verbose_name cannot be set for a @property called name, but short_description can be used instead:

class Person(models.Model):
    first_name = models.CharField('Given name', max_length=255)
    last_name = models.CharField('Family name ', max_length=255)

    @property
    def name(self):
        return '%s %s' % (self.first_name, self.last_name)

    name.fget.short_description = 'First and last name'

This may not work with all Django admin classes, but it will work with the basic one.

This uses the fget object created by @property and sets a short_description property in it. Django looks for that property and uses it if available.

Mr. Lance E Sloan
  • 3,297
  • 5
  • 35
  • 50
3

In the documentation the following code is suggested to give a property short description:

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

    def my_property(self):
        return self.first_name + ' ' + self.last_name
    my_property.short_description = "Full name of the person"

    full_name = property(my_property)

class PersonAdmin(admin.ModelAdmin):
    list_display = ('full_name',)

However, this approach does not work when using Django-tables2 so the following code is needed in order to change a column name:

columnName = tables.Column(verbose_name='column name')

Django-tables2: Change text displayed in column title

so finally I think you should use custom forms and override field verbose_name if you face such a problem.

smrf
  • 349
  • 3
  • 16