admin.py — A Back Office for Free
The cookbook's editor needs to add recipes, fix typos and delete duplicates, and she does not write Python. Building those screens by hand would take days. Django's admin gives you them in about five lines, because it already knows your models.
The rule
Register a model, get a back office; customise with a ModelAdmin.
The simplest registration:
# recipes/admin.py
from django.contrib import admin
from .models import Recipe
admin.site.register(Recipe)Then create an account that can log in:
python manage.py createsuperuserStart the server and open /admin/. The project's urls.py already routes admin/ there. Log in and you will see Recipes with pages to list, add, edit and delete them. Each row shows the model's __str__, which is why that method is worth writing.
A ModelAdmin class shapes those pages:
@admin.register(Recipe)
class RecipeAdmin(admin.ModelAdmin):
list_display = ["title", "minutes", "created"] # columns in the list
list_filter = ["created"] # sidebar filter
search_fields = ["title"] # search box
prepopulated_fields = {"slug": ("title",)} # fill slug from title@admin.register(Recipe) does the same as admin.site.register(Recipe, RecipeAdmin), written as a decorator. Use one or the other, not both; registering a model twice is an error.
The admin respects Django's users and permissions: only accounts marked as staff can log in, and each can be allowed to view, add, change or delete particular models. A superuser can do everything.
Keep its purpose in mind. The admin is an internal tool for trusted people managing data. It is not the public site; readers of the cookbook use the views and templates you write.
The shortcut
For any admin wish, finish the sentence "In the list I want …" and map it to one option. Columns → list_display. A search box → search_fields. Filters in the sidebar → list_filter. A field filled in for me → prepopulated_fields.
"I can't see Recipes at all"
The model is not registered. Add
@admin.register(Recipe).
Drills
Answer fast — trust the rule.
The admin loads, but Recipe does not appear. What is the most likely fix?
Which command creates an account that can log in to the admin with full rights?
Which option adds columns to the admin's list of recipes?
Who should use the Django admin?
Remember
- Register a model, get a back office; customise it with a
ModelAdmin. - Map each wish to one option: columns, search, filters, prepopulated fields.
- Trap: the admin is for staff, not a substitute for the public site.
