SaeX
SaeX

Reputation: 18691

Verbose name for @property

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?

Upvotes: 17

Views: 8948

Answers (3)

Tom
Tom

Reputation: 1

When using a serializer field of django's rest_framework package, you can change the label attribute of the field to change the verbose name

Upvotes: 0

Mr. Lance E Sloan
Mr. Lance E Sloan

Reputation: 3387

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.

Upvotes: 18

smrf
smrf

Reputation: 361

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.

Upvotes: 3

Related Questions