Customizing the Admin Interface

You can customize the way the admin interface looks and behaves in a number of ways. As it stands now, the change list for our books shows only the string representation of the model we added to its __str__. This works fine for just a few books, but if we had hundreds or thousands of books, it would be very hard to locate a single needle in the haystack. However, we can easily add some display, searching, and filtering functions to this interface. Change the Admin declaration as follows:

class Book(models.Model):
title = models.CharField(maxlength=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()

class Admin:
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publisher', 'publication_date')
ordering = ('-publication_date',)
search_fields = ('title',)

These four lines of code dramatically change our list interface, as shown in Figure 6-8.

image024

Figure 6-8. Modified change list page

 

Each of those lines instructed the admin interface to construct a different piece of this interface:

  • The list_display option controls which columns appear in the change list table. By default, the change list displays only a single column that contains the object’s string representation. Here, we’ve changed that to show the title, publisher, and publication date.
  • The list_filter option creates the filtering bar on the right side of the list. We’ve allowed filtering by date (which allows you to see only books published in the last week, month, etc.) and by publisher.
  • You can instruct the admin interface to filter by any field, but foreign keys, dates, Booleans, and fields with a choices attribute work best. The filters show up as long as there are at least 2 values to choose from.
  • The ordering option controls the order in which the objects are presented in the admin interface. It’s simply a list of fields by which to order the results; prefixing a field with a minus sign reverses the given order. In this example, we’re ordering by publication date, with the most recent first.
  • Finally, the search_fields option creates a field that allows text searches. It allows searches by the title field (so you could type Django to show all books with “Django” in the title).

Using these options you can, with only a few lines of code, make a very powerful, production-ready interface for data editing.

Back to Tutorial

Using the Admin Interface
Filter Configuration

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?