Skip to content
thesarfo

Note

Customizing the Admin List Page

Using a ModelAdmin subclass to control list_display, list_editable, list_per_page, and ordering on the admin change list.

views 0

Let’s say you want to customize the page that lists your models and its fields. You can do that by creating a class in the admin.py file inside the app that contains the models you wanna display. and in that class you specify the fields that you wanna display. see below

from django.contrib import admin
from . import models
class ProductAdmin(admin.ModelAdmin): #this class can be called anything
list_display = ['title', 'unit_price']

Now that we have the class, we have to specify it when we are registering the model. see below

admin.site.register(models.Product, ProductAdmin)

Now when you refresh the product list page, you will see the product titles, as well as their unit prices. This is one way to do it.

Another way to do it will be to use the register decorator function. see below

from django.contrib import admin
from . import models
@admin.register(models.Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ['title', 'unit_price']
admin.site.register(models.Product)
# when we do it this way we dont have to add the modelAdmin class to our register method.

There are a bunch of stuff we can do under the ProductAdmin class. see below

  1. list_editable = ['unit_price'] - means you can edit the unit prices in the admin panel
  2. list_per_page = 10 - means you will only see 10 stuff on each page, it paginates the rest
  3. ordering = ['first_name', 'last_name'] - similar alternative to the Meta class ordering.