Daniel W.
Daniel W.

Reputation: 32260

Setting verbose name of function field in Django

I have a simple Model like this:

class Artist(models.Model):
    class Meta:
        verbose_name = "Artist"
        verbose_name_plural = "Artists"

    name = models.CharField(max_length=128, unique=True, blank=False)

    def test_function(self):
        return 'xyz'

And Admin:

class ArtistAdmin(admin.ModelAdmin):
    list_display = ['name', 'test_function']
    search_fields = ['name']
    readonly_fields = []

Now in the list view, the function field is verbosed as TEST_FUNCTION:

list view in django admin

In a normal field I would use the Field.verbose_name parameter.

How do I achieve that with the function field?

In object terms thinking, I would try to return a mocked CharField instead of a simple string. Would this work somehow?

Upvotes: 4

Views: 2413

Answers (2)

Daniel
Daniel

Reputation: 11

From this section of the Django docs I found that there is a decorator you can use to achieve custom names for these methods.

class PersonAdmin(admin.ModelAdmin):
    list_display = ["upper_case_name"]

    @admin.display(description="Name")
    def upper_case_name(self, obj):
        return f"{obj.first_name} {obj.last_name}".upper()

In this case there will be a "Name" field with the value returned from the "upper_case_name" method".

Upvotes: 0

Jaap Joris Vens
Jaap Joris Vens

Reputation: 3550

As per the documentation, you can give the function an attribute called short_description:

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

    def upper_case_name(self, obj):
        return ("%s %s" % (obj.first_name, obj.last_name)).upper()
    upper_case_name.short_description = 'Name'

If set, the Django Admin will show this description rather than the function name. Even better, change it into _('Name') to allow for different translations!

Upvotes: 5

Related Questions