Rivadiz Rivadiz - 2 months ago 11
Python Question

Custom value for list_display item on Django admin

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

Answer

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.

Comments