Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom value for list_display item on Django admin

Tags:

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

like image 687
Rivadiz Avatar asked Oct 08 '15 11:10

Rivadiz


People also ask

What is List_display Django?

It provides a simple UI for creating, editing and deleting data defined with the Django ORM. In this article we are going to enable the admin user interface for a simple model and customize it from a simple list view to a more user friendly table like interface.

What is Prepopulated_fields in Django admin?

The attribute prepopulated_fields tells the admin application to automatically fill the field slug - in this case with the text entered into the name field.


2 Answers

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.

like image 84
solarissmoke Avatar answered Oct 02 '22 17:10

solarissmoke


It would be better if you use empty_value_display

empty_value_display
This attribute overrides the default display value for record’s fields that are empty (None, empty string, etc.). The default value is - (a dash).

class AuthorAdmin(admin.ModelAdmin):
    list_display = ('sub_title',)
    sub_title.empty_value_display = 'Not Available'

This is for django >= 1.9

like image 41
durdenk Avatar answered Oct 02 '22 16:10

durdenk