djangodjango-modelsdjango-admin

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?


Solution

  • 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!