admin.ModelAdmin.list_display

ModelAdmin.list_display

Set list_display to control which fields are displayed on the change list page of the admin.

Example:

list_display = ('first_name', 'last_name')

If you don’t set list_display, the admin site will display a single column that displays the __str__() (__unicode__() on Python 2) representation of each object.

You have four possible values that can be used in list_display:

  • A field of the model. For example:

    class PersonAdmin(admin.ModelAdmin):
        list_display = ('first_name', 'last_name')
    
  • A callable that accepts one parameter for the model instance. For example:

    def upper_case_name(obj):
        return ("%s %s" % (obj.first_name, obj.last_name)).upper()
    upper_case_name.short_description = 'Name'
    
    class PersonAdmin(admin.ModelAdmin):
        list_display = (upper_case_name,)
    
  • A string representing an attribute on the ModelAdmin. This behaves same as the callable. For example:

    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'
    
  • A string representing an attribute on the model. This behaves almost the same as the callable, but self in this context is the model instance. Here’s a full model example:

    from django.db import models
    from django.contrib import admin
    
    class Person(models.Model):
        name = models.CharField(max_length=50)
        birthday = models.DateField()
    
        def decade_born_in(self):
            return self.birthday.strftime('%Y')[:3] + "0's"
        decade_born_in.short_description = 'Birth decade'
    
    class PersonAdmin(admin.ModelAdmin):
        list_display = ('name', 'decade_born_in')
    

A few special cases to note about list_display:

  • If the field is a ForeignKey, Django will display the __str__() (__unicode__() on Python 2) of the related object.
  • 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, give your model a custom method, and add that method’s name to list_display. (See below for more on custom methods in list_display.)
  • If the field is a BooleanField or NullBooleanField, Django will display a pretty “on” or “off” icon instead of True or False.
  • If the string given is a method of the model, ModelAdmin or a callable, Django will HTML-escape the output by default. To escape user input and allow your own unescaped tags, use format_html().

    Here’s a full example model:

    from django.db import models
    from django.contrib import admin
    from django.utils.html import format_html
    
    class Person(models.Model):
        first_name = models.CharField(max_length=50)
        last_name = models.CharField(max_length=50)
        color_code = models.CharField(max_length=6)
    
        def colored_name(self):
            return format_html(
                '<span style="color: #{};">{} {}</span>',
                self.color_code,
                self.first_name,
                self.last_name,
            )
    
    class PersonAdmin(admin.ModelAdmin):
        list_display = ('first_name', 'last_name', 'colored_name')
    

    Deprecated since version 1.9: In older versions, you could add an allow_tags attribute to the method to prevent auto-escaping. This attribute is deprecated as it’s safer to use format_html(), format_html_join(), or mark_safe() instead.

  • If the value of a field is None, an empty string, or an iterable without elements, Django will display - (a dash). You can override this with AdminSite.empty_value_display:

    from django.contrib import admin
    
    admin.site.empty_value_display = '(None)'
    

    You can also use ModelAdmin.empty_value_display:

    class PersonAdmin(admin.ModelAdmin):
        empty_value_display = 'unknown'
    

    Or on a field level:

    class PersonAdmin(admin.ModelAdmin):
        list_display = ('name', 'birth_date_view')
    
        def birth_date_view(self, obj):
             return obj.birth_date
    
        birth_date_view.empty_value_display = 'unknown'
    
    New in Django 1.9:

    The ability to customize empty_value_display was added.

  • If the string given is a method of the model, ModelAdmin or a callable that returns True or False Django will display a pretty “on” or “off” icon if you give the method a boolean attribute whose value is True.

    Here’s a full example model:

    from django.db import models
    from django.contrib import admin
    
    class Person(models.Model):
        first_name = models.CharField(max_length=50)
        birthday = models.DateField()
    
        def born_in_fifties(self):
            return self.birthday.strftime('%Y')[:3] == '195'
        born_in_fifties.boolean = True
    
    class PersonAdmin(admin.ModelAdmin):
        list_display = ('name', 'born_in_fifties')
    
  • The __str__() (__unicode__() on Python 2) method is just as valid in list_display as any other model method, so it’s perfectly OK to do this:

    list_display = ('__str__', 'some_other_field')
    
  • Usually, elements of list_display that aren’t actual database fields can’t be used in sorting (because Django does all the sorting at the database level).

    However, if an element of list_display represents a certain database field, you can indicate this fact by setting the admin_order_field attribute of the item.

    For example:

    from django.db import models
    from django.contrib import admin
    from django.utils.html import format_html
    
    class Person(models.Model):
        first_name = models.CharField(max_length=50)
        color_code = models.CharField(max_length=6)
    
        def colored_first_name(self):
            return format_html(
                '<span style="color: #{};">{}</span>',
                self.color_code,
                self.first_name,
            )
    
        colored_first_name.admin_order_field = 'first_name'
    
    class PersonAdmin(admin.ModelAdmin):
        list_display = ('first_name', 'colored_first_name')
    

    The above will tell Django to order by the first_name field when trying to sort by colored_first_name in the admin.

    To indicate descending order with admin_order_field you can use a hyphen prefix on the field name. Using the above example, this would look like:

    colored_first_name.admin_order_field = '-first_name'
    

    admin_order_field supports query lookups to sort by values on related models. This example includes an “author first name” column in the list display and allows sorting it by first name:

    class Blog(models.Model):
        title = models.CharField(max_length=255)
        author = models.ForeignKey(Person, on_delete=models.CASCADE)
    
    class BlogAdmin(admin.ModelAdmin):
        list_display = ('title', 'author', 'author_first_name')
    
        def author_first_name(self, obj):
            return obj.author.first_name
    
        author_first_name.admin_order_field = 'author__first_name'
    
  • Elements of list_display can also be properties. Please note however, that due to the way properties work in Python, setting short_description on a property is only possible when using the property() function and not with the @property decorator.

    For example:

    class Person(models.Model):
        first_name = models.CharField(max_length=50)
        last_name = models.CharField(max_length=50)
    
        def my_property(self):
            return self.first_name + ' ' + self.last_name
        my_property.short_description = "Full name of the person"
    
        full_name = property(my_property)
    
    class PersonAdmin(admin.ModelAdmin):
        list_display = ('full_name',)
    
  • The field names in list_display will also appear as CSS classes in the HTML output, in the form of column-<field_name> on each <th> element. This can be used to set column widths in a CSS file for example.
  • Django will try to interpret every element of list_display in this order:

    • A field of the model.
    • A callable.
    • A string representing a ModelAdmin attribute.
    • A string representing a model attribute.

    For example if you have first_name as a model field and as a ModelAdmin attribute, the model field will be used.

doc_Django
2016-10-09 18:33:50
Comments
Leave a Comment

Please login to continue.