Custom value for list_display item on Django admin

Issue

In a model I have a subtitle field, which is populated with None if no value exists for the field for the given object.

Is there any way to display the value to something custom (like Not Available or Not Applicable than just displaying (None)

field

sub_title = models.CharField(max_length=255, null=True, blank=True) 

admin

 list_display = 'sub_title', 

enter image description here

PS: I want None in the database, while a custom value just on admin panel.

thanks

Solution

list_display can accept a callable, so you can do this:

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('get_sub_title',)

    def get_sub_title(self, obj):
        if obj.sub_title:
            return obj.sub_title
        else:
            return 'Not Available'

    get_sub_title.short_description = 'Subtitle'

The docs provide several other options for providing a callable.

Answered By – solarissmoke

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published