Menu
CoddyTech

Customizing the Admin

Part of the Models and the Admin section of Coddy's Django journey. Lesson 21 of 23.

The admin's list of books has one column, each book's __str__, and no way to find anything. A ModelAdmin class, registered with the decorator, changes that. For a Loan with a ForeignKey book:

@admin.register(Loan)
class LoanAdmin(admin.ModelAdmin):
    list_display = ["book", "friend", "lent_on", "returned"]
    search_fields = ["friend", "book__title"]
    list_filter = ["returned", "lent_on"]

list_display picks the columns; a ForeignKey column shows the related row's __str__, and a many-to-many field cannot be a column. search_fields adds a search box. To search through a ForeignKey, name a field of the other model after two underscores, book__title: book alone is a link, not text, and crashes the search. list_filter adds a sidebar of filters.

The decorator does the same as admin.site.register(Loan, LoanAdmin). Register each model once: a second time stops the site with AlreadyRegistered.

challenge icon

Challenge

Easy

In books/admin.py, give Book a BookAdmin in place of its plain registration. The Books list should have:

  • columns for title, author, year, genre and is_read
  • a search box that finds books by title or by author's name
  • a sidebar that filters by genre and is_read

Press Run, log in again and search for herbert.

Try it yourself

from django.contrib import admin

from .models import Author, Book, Tag

admin.site.register(Book)
admin.site.register(Author)
admin.site.register(Tag)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Models and the Admin

Practice on your own: Django playground