Django Admin
The Django admin is a complete back-office website generated from your models. Register a model and staff users can list, search, filter, create, edit and delete its rows — no views, templates or forms to write. It's one of Django's most loved features and perfect for internal tools, content editing and inspecting data during development.
Note: The admin is meant for trusted staff, not for your site's public visitors. Build regular views for everything customers see.
Enabling the admin
A project created with startproject already has everything wired up: django.contrib.admin in INSTALLED_APPS and this line in the root URLconf:
# mysite/urls.py
from django.contrib import admin
from django.urls import path
urlpatterns = [
path("admin/", admin.site.urls),
]You need a user who is allowed in. createsuperuser asks for a name, email and password:
python manage.py createsuperuserUsername (leave blank to use 'linh'): admin
Email address: admin@example.com
Password:
Password (again):
Superuser created successfully.
Start runserver and open http://127.0.0.1:8000/admin/ to log in.
Registering a model
Models appear in the admin only after you register them, normally in the app's admin.py:
# books/admin.py
from django.contrib import admin
from .models import Book
admin.site.register(Book)That single line gives you a list page, an add form, a change form and a delete confirmation page for Book. The list shows each object's __str__(), so define a good one on your models.
Customising with ModelAdmin
To control how a model is shown, register it with a ModelAdmin subclass. The @admin.register decorator is the usual style:
# books/admin.py
from django.contrib import admin
from .models import Book
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ["title", "author", "year", "in_stock"] # columns on the list page
list_filter = ["in_stock", "year"] # sidebar filters
search_fields = ["title", "author"] # search box
ordering = ["title"]
list_per_page = 25
prepopulated_fields = {"slug": ["title"]} # fill slug while typing
readonly_fields = ["created"]| Option | Effect |
|---|---|
list_display |
columns shown on the change list (fields, methods or callables) |
list_filter |
filters in the right sidebar |
search_fields |
fields searched by the search box (icontains by default) |
ordering |
default sort order of the list |
list_editable |
fields editable directly on the list page |
fields / fieldsets |
which fields the edit form shows, and in what groups |
readonly_fields |
shown but not editable |
inlines |
edit related objects (e.g. chapters) on the parent's page |
actions |
bulk actions for selected rows |
The admin, running for real
The admin is just Django views, so the playground can run it too. This example installs the admin's apps, runs their migrations, registers a model, logs in a superuser with the test client and then reads the list page:
import sys, types, re, django
from django.conf import settings
sys.modules["demo"] = types.ModuleType("demo")
sys.modules["demo"].__file__ = "demo/__init__.py"
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(
SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
INSTALLED_APPS=["django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes",
"django.contrib.sessions", "django.contrib.messages", "demo"],
MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True,
"OPTIONS": {"context_processors": [
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages"]}}],
PASSWORD_HASHERS=["django.contrib.auth.hashers.MD5PasswordHasher"], # fast, demo only
)
django.setup()
from django.core.management import call_command
from django.db import models, connection
from django.contrib import admin
from django.contrib.auth.models import User
from django.urls import path
from django.test import Client
call_command("migrate", verbosity=0) # tables for auth, admin, sessions …
class Book(models.Model):
title = models.CharField(max_length=100)
year = models.IntegerField()
class Meta:
app_label = "demo"
def __str__(self):
return self.title
with connection.schema_editor() as editor:
editor.create_model(Book)
Book.objects.create(title="Dune", year=1965)
Book.objects.create(title="Emma", year=1815)
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ["title", "year"]
ordering = ["year"]
urls.urlpatterns = [path("admin/", admin.site.urls)]
client = Client()
r = client.get("/admin/demo/book/")
print("anonymous:", r.status_code, r["Location"])
boss = User.objects.create_superuser("boss", "boss@example.com", "s3cret")
client.force_login(boss)
html = client.get("/admin/demo/book/").content.decode()
print("titles:", re.findall(r'class="field-title"><a [^>]*>(.*?)</a>', html))
print("years: ", re.findall(r'class="field-year">(.*?)</td>', html))anonymous: 302 /admin/login/?next=/admin/demo/book/
titles: ['Emma', 'Dune']
years: ['1815', '1965']
Anonymous visitors are redirected to the login page; the logged-in superuser sees the rows sorted by ordering. The URL pattern of admin pages is always /admin/<app_label>/<model>/.
Adding objects through the admin
The admin's add form is a normal Django form. Posting valid data creates the row and redirects back to the list:
import sys, types, django
from django.conf import settings
sys.modules["demo"] = types.ModuleType("demo")
sys.modules["demo"].__file__ = "demo/__init__.py"
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(
SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
INSTALLED_APPS=["django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes",
"django.contrib.sessions", "django.contrib.messages", "demo"],
MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True,
"OPTIONS": {"context_processors": [
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages"]}}],
PASSWORD_HASHERS=["django.contrib.auth.hashers.MD5PasswordHasher"],
)
django.setup()
from django.core.management import call_command
from django.db import models, connection
from django.contrib import admin
from django.contrib.admin.models import LogEntry
from django.contrib.auth.models import User
from django.urls import path
from django.test import Client
call_command("migrate", verbosity=0)
class Book(models.Model):
title = models.CharField(max_length=100)
year = models.IntegerField()
class Meta:
app_label = "demo"
def __str__(self):
return self.title
with connection.schema_editor() as editor:
editor.create_model(Book)
admin.site.register(Book)
urls.urlpatterns = [path("admin/", admin.site.urls)]
client = Client()
client.force_login(User.objects.create_superuser("boss", "boss@example.com", "s3cret"))
r = client.post("/admin/demo/book/add/", {"title": "Persuasion", "year": "1817"})
print(r.status_code, r["Location"])
print(Book.objects.values_list("title", "year").get())
r = client.post("/admin/demo/book/add/", {"title": "", "year": "soon"})
print("invalid form ->", r.status_code, "(form shown again with errors)")
print(Book.objects.count(), "book(s) in the database")
entry = LogEntry.objects.get()
print("history:", entry.user, "added", entry.object_repr)302 /admin/demo/book/
('Persuasion', 1817)
invalid form -> 200 (form shown again with errors)
1 book(s) in the database
history: boss added Persuasion
Every change made through the admin is recorded in LogEntry — that's the "History" button on each object's page.
Custom columns and actions
list_display accepts methods, and actions add entries to the "Action" dropdown that run on the selected rows:
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ["title", "year", "age"]
actions = ["mark_out_of_stock"]
@admin.display(description="Age (years)")
def age(self, obj):
return 2026 - obj.year
@admin.action(description="Mark selected books as out of stock")
def mark_out_of_stock(self, request, queryset):
updated = queryset.update(in_stock=False)
self.message_user(request, f"{updated} books updated.")Tip: Change the headings with
admin.site.site_header = "Bookshelf admin"andadmin.site.site_title = "Bookshelf"in anyadmin.py.
Test yourself
Which command creates a user who can log into the admin?
- python manage.py adduser
- python manage.py createsuperuser
- python manage.py migrate admin
- django-admin login
Which ModelAdmin option chooses the columns on the list page?
- fields
- list_display
- search_fields
- columns
Where do you normally register models with the admin?
- settings.py
- urls.py
- the app's admin.py
- models.py inside Meta