Django: How to use list_display to display fields on admin list page

Published on Aug. 22, 2023, 12:12 p.m.

To control which fields are displayed on the change list page, set list _ display.

list_display = ('first_name', 'last_name')

If you don’t set list_display, the admin site will display a single column .
There are four types of values that can be used.All but the simplest may use the display() decorator.

Name of a model field.

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

A callable that accepts one argument .

@admin.display(description='Name')
def upper_case_name(obj):
    return ("%s %s" % (obj.first_name, obj.last_name)).upper()

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

A string representing a ModelAdmin method .

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

    @admin.display(description='Name')
    def upper_case_name(self, obj):
        return ("%s %s" % (obj.first_name, obj.last_name)).upper()

A string representing a model attribute or method.

from django.contrib import admin
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()

    @admin.display(description='Birth decade')
    def decade_born_in(self):
        return '%d’s' % (self.birthday.year // 10 * 10)

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

A few special cases to note about it .

  • If the field is a ForeignKey, Django will display the str .
  • ManyToManyField fields aren’t supported, because that would entail executing a separate SQL statement for each row in the table.If you want to do this nonetheless , add that method’s name to list_display.
  • If the field is a BooleanField, Django will display a pretty “yes”, “no”, or “unknown” icon instead.
  • ModelAdmin or a callable, Django will HTML- escape the output by default.To escape user input and allow your own unescaped tags.

https://docs.djangoproject.com/en/4.1/ref/contrib/admin/