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.