Displaying Models
Learn how to display your Django models on the admin page.
We'll cover the following
Displaying the model
You learned how to populate the database in the previous lesson. Now you will see the populated databases in your Django Admin Page.
If you click on the The Authors
link on your admin page, will it show the data in our Author
database table, but it will only show the name of the author. What about the other fields, such as the creationDate
or updatedDate
?
To display them, you will have to create a new class AuthorAdmin
, which will inherit admin.ModelAdmin
in the admin.py
and register this new class.
from django.contrib import admin
from sample_app.models import *
class AuthorAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['name']}),
]
list_display = ('name','createdDate','updatedDate',)
## Register your models here.
admin.site.register(Author, AuthorAdmin)
admin.site.register(Question)
admin.site.register(Choice)
Or you can use the keyword @admin.register
like this (in this case, you will need to remove the line admin.site.register(Author, AuthorAdmin)
from the above snippet):
...
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
...
The list_display
contains all the attributes that will be displayed on the Admin Page for that model. Don’t worry about the working of fieldsets
, as we will see what it does in the next lesson.
By default, Django admin paginates results by 100. You can change this behaviour by setting a list_per_page
value (e.g., list_per_page = 50
) in your model admin class.
Get hands-on with 1400+ tech skills courses.