The Django admin: a back office on day one, and where it stops
TL;DR
Difficulty: Beginner
The Django admin is a generated back office for trusted staff, and its own documentation says it should stay one.
- People who come to change a record belong in the admin. People who come to finish a task, people who are not staff, and screens that must update live belong on pages you build.
- A few dozen lines of ModelAdmin give you lists, filters with Django 5.0 facet counts, search, inlines, autocomplete, actions and permissions.
- Bulk actions that call update() skip save() and signals, so put every side effect in one service function that every screen calls.
- Scope each manager to their own rows in get_queryset, protect the login with a second factor and a non obvious path, and keep the admin as the spare key after custom pages arrive.
Django gives you a complete back office on the first afternoon of a project. The question is how far it carries you before your managers start fighting it. Here is the whole admin from the documentation, built on a chain of bicycle repair workshops, with the one rule that tells you when a screen needs its own page.
The question behind this chapter
Every web application needs a back office. Somebody has to fix a misspelt customer name, correct a stock count after a delivery, find last Tuesday's invoice and see which bookings are stuck. In most frameworks you build those screens yourself. In Django, one of them arrives with the framework: the admin, a complete management interface generated from your models.
So the question I hear from founders and developers alike is a fair one. How far can I get with the Django admin as my back office, and when should I build my own pages instead?
This chapter answers it with the same invented business as the rest of the series. Cogwell Cycles runs six bicycle repair workshops around Sheffield (cogwellcycles.example), with 38 mechanics, about 1,150 repair bookings a week, 9,000 active customers and 2,400 spare parts in stock. The founder is Hannah, the developers are Priya and Owen. In the decision chapter they built a two week spike in both frameworks, and this series follows the Django version of the spike, with the same models as the Rails series: Workshop, Mechanic, Customer, Bike, Booking, JobCard, Part, PartUsage and Invoice. If you have not met those models yet, the ORM chapter builds them.
Everything here is written for Django 5.0, released on 4 December 20231, and Python 3.12.
The short answer: records or tasks
Here is the rule I use, and it is the most useful thing in this chapter.
The admin fits people who come to change a record. It breaks for people who come to finish a task.
A record is a row in a table: a customer, a part, an invoice. Someone who thinks in records arrives with a question like "what is this customer's email address?" or "why does part 4471 show 12 in stock?". They find the row, look at it, perhaps change a field, and leave. The admin is superb at this, because it is a generic editor for rows, and it is generated for free.
A task is a piece of work with a beginning, an order and an end: take in a bike, repair it, tell the customer, hand it back. Someone who thinks in tasks does not care which table a fact lives in. They want the next thing to do, in the order the work happens, with as few taps as possible. The admin knows nothing about your tasks. It only knows your tables.
Three signals tell you that a screen is task shaped and has outgrown the admin. Any one of them is enough:
- The person is not trusted staff. Customers, and anyone who should not see the whole database, need their own pages.
- The work crosses several models in a fixed order. If doing the job means opening three change forms in sequence, it is a workflow, and the admin will make every user carry that sequence in their head.
- The screen has to change while people look at it. Several people working on the same thing at once, live, is not what a list of rows and a save button were designed for.
Example: Cogwell's back office jobs, sorted
Priya wrote down every back office job Hannah's managers described during the spike and sorted them with the record or task question.
| Job | Who does it | Record or task | Signal | Where it lives |
|---|---|---|---|---|
| Correct a customer's phone number | Managers | Record | none | Admin |
| Look up a bike by frame number | Managers | Record | none | Admin |
| Adjust stock after a delivery | Managers | Record | none | Admin |
| Find and view an invoice | Managers, accounts | Record | none | Admin |
| Check which bookings a mechanic has tomorrow | Managers | Record (a filtered list) | none | Admin |
| Move job cards through waiting, in repair, ready | Mechanics, managers | Task | crosses models, changes live | Custom page |
| Take a booking online | Customers | Task | not staff | Custom page |
| Read the nightly reorder report | Managers | Record (a report) | none | Admin custom view |
| Log parts used on a repair | Mechanics | Task | not office staff, on a tablet | Custom page, later the mobile app |
Six of nine jobs are record shaped. That is typical, and it is why the admin is worth so much on day one. The other three are exactly the screens customers and mechanics touch all day, which is why the admin is never the whole answer.
What the Django documentation says the admin is for
Before building anything on the admin, read what its authors say it is. The reference documentation is unusually direct. It limits the admin's recommended use to an organisation's internal management tool, and says it is not meant for building your entire front end around2.
The tutorial explains where that comes from. Django was written in a newsroom, where editors entered stories and the public read them on a separate site, and the admin was the editors' tool. In the tutorial's words, "The admin isn't intended to be used by site visitors."3 Django's own history fits: it grew out of World Online, the web department of a newspaper in Lawrence, Kansas, from 2003, and was released as open source in summer 20054.
Read those two sentences together and you have the design brief. The admin assumes the person in front of it is trusted, understands the data model, and is allowed to be wrong in front of the database now and then. Everything that is great about it follows from that assumption, and so does everything that goes wrong when people ignore it.
Example: who gets an admin login at Cogwell
Applying the brief, Hannah's back office has three kinds of people:
- Head office (Hannah and the accounts person): every workshop, every model, read and write, except deleting invoices.
- Workshop managers (six people, one per workshop): their own workshop's bookings, job cards, customers and parts.
- Mechanics (38 people): no admin login at all. They work on the workshop board and, later, the mobile app.
That decision, made before a line of admin code, removes most of the security and usability trouble later in this chapter. Thirty eight mechanics with admin logins would be 38 people with a generic database editor on a tablet in a workshop. Eight trusted people with scoped access is a back office.
From nothing to a working back office in one file
The admin is switched on in every new project: django.contrib.admin is in INSTALLED_APPS and the URL configuration includes path("admin/", admin.site.urls)2. What you add is one admin.py per app, in which you register models and describe how their lists and forms should behave. The class that holds that description is called a ModelAdmin.
The options you will use most, all from the reference documentation2:
list_display: the columns on the list page (the admin calls it the change list).list_filter: the filters offered beside the list.search_fields: the fields the search box looks in.date_hierarchy: a row of date links above the list, to drill down by year, month and day.ordering: the default sort.list_select_related: which related tables to fetch in the same query, so the list does not run one query per row.
Example: the bookings list for managers
Bookings live in the bookings app of the Cogwell project. This is the whole admin for them:
# bookings/admin.py
from django.contrib import admin
from .models import Bike, Booking, Customer
@admin.register(Booking)
class BookingAdmin(admin.ModelAdmin):
# Columns on the list page
list_display = ["starts_at", "workshop", "mechanic", "customer", "bike"]
# Filters offered beside the list
list_filter = ["workshop", "mechanic", "starts_at"]
# The search box looks in these fields (double underscore follows a relation)
search_fields = ["customer__last_name", "customer__email", "bike__frame_number"]
# Year, month and day links above the list
date_hierarchy = "starts_at"
ordering = ["-starts_at"]
# One query with joins instead of one query per row
list_select_related = ["workshop", "mechanic", "customer", "bike"]
What a manager gets from those 13 lines of code:
- A list of bookings, newest first, 100 to a page by default2.
- Filters by workshop, mechanic and date, combined freely.
- A search box that finds "Patel" or a frame number.
- Date links: click 2024, then April, then 16, and see that day's bookings.
- A form to add and edit bookings, with validation from the model, and a history of every change made through the admin.
Customers and bikes get two even shorter classes. On the first afternoon of the spike, Priya had a back office that would have taken a week or more to build by hand. That is the admin's whole argument, and it is a strong one.
Facet counts: the Django 5.0 addition that managers notice
Django 5.0 added facet counts to the admin's filters1. A facet count is the number next to each filter option, telling you how many rows you would see if you clicked it, given the filters already applied. "Waiting (14)", "In repair (9)", "Ready (6)" turns a filter list into a small dashboard.
By default the counts appear only when someone toggles them on in the interface. The new ModelAdmin.show_facets setting controls this with three values: ShowFacets.ALWAYS, ShowFacets.ALLOW (the default, shown when the _facets query parameter is present) and ShowFacets.NEVER2.
There is a cost, and the documentation states it plainly: each filter adds queries to the list page, and on large datasets that can cause performance problems, in which case ShowFacets.NEVER switches them off2.
Example: the job cards list with live counts
# repairs/admin.py
from django.contrib import admin
from .models import JobCard
@admin.register(JobCard)
class JobCardAdmin(admin.ModelAdmin):
list_display = ["id", "booking", "status", "updated_at"]
# Filters across the relation to the booking
list_filter = ["status", "booking__workshop", "booking__mechanic"]
# Always show how many cards each filter option would return
show_facets = admin.ShowFacets.ALWAYS
list_select_related = ["booking__customer", "booking__workshop"]
A manager at the Hillsborough workshop filters by her workshop and sees, without clicking anything else, "Waiting (11), In repair (7), Ready (4), Collected (312)". Three filters mean a handful of extra count queries per page view. With six managers glancing at it a few dozen times a day, that is nothing. If job cards ever reach the millions of rows, Priya will turn the counts off for the status filter's busiest views first and measure again.
Editing related records together: inlines, autocomplete and read only fields
Real records come in families. A job card has parts used on it. An invoice has lines. Three admin features handle this.
Inlines show related rows inside the parent's form. TabularInline shows them as a compact table and StackedInline as full forms, and extra sets how many empty rows appear for new entries. It defaults to 32.
Autocomplete fields replace a dropdown with a search box for a related record. A dropdown that lists 2,400 parts or 9,000 customers is slow to render and impossible to use. autocomplete_fields needs one thing: the related model's own ModelAdmin must define search_fields, because the autocomplete uses them. The documentation adds a sensible guard: users need the view or change permission on the related model to use it2.
Read only fields show computed or protected values without letting anyone edit them. A method on the ModelAdmin listed in readonly_fields can render anything, such as a photo preview.
Example: a job card with its parts and photos
First the parts admin, which the autocomplete depends on:
# parts/admin.py
from django.contrib import admin
from .models import Part
@admin.register(Part)
class PartAdmin(admin.ModelAdmin):
list_display = ["sku", "name", "in_stock", "reorder_level", "needs_reorder"]
# "^" means "starts with", which can use an index on sku
search_fields = ["^sku", "name"]
@admin.display(boolean=True, description="Reorder?")
def needs_reorder(self, obj):
return obj.in_stock <= obj.reorder_level
Then the job card form, extended with the parts used and the before and after photos:
# repairs/admin.py (extended)
from django.contrib import admin
from django.utils.html import format_html_join
from parts.models import PartUsage
from .models import JobCard
class PartUsageInline(admin.TabularInline):
model = PartUsage
extra = 0 # no empty rows unless the manager clicks "Add another"
autocomplete_fields = ["part"] # a search box instead of 2,400 options
@admin.register(JobCard)
class JobCardAdmin(admin.ModelAdmin):
list_display = ["id", "booking", "status", "updated_at"]
list_filter = ["status", "booking__workshop", "booking__mechanic"]
show_facets = admin.ShowFacets.ALWAYS
list_select_related = ["booking__customer", "booking__workshop"]
search_fields = ["=id", "booking__customer__last_name", "booking__bike__frame_number"]
readonly_fields = ["photos", "created_at", "updated_at"]
inlines = [PartUsageInline]
@admin.display(description="Photos")
def photos(self, obj):
pairs = [(obj.photo_before, "Before repair"), (obj.photo_after, "After repair")]
# format_html_join escapes every value, so a file name cannot inject HTML
return format_html_join(
" ",
'<img src="{}" alt="{}" width="160">',
((photo.url, label) for photo, label in pairs if photo),
)
A manager opens job card 18342 and sees the booking, the status, both photos with alt text, and a small table of parts used, where adding a brake pad means typing "brake" and picking from a short list. Forty lines of code across two files. Building the same form by hand, with the autocomplete endpoint and the inline formset, is a few days of careful work.
The table of admin features you will actually use
Here are the features that matter for a back office, what each does, and what it is good for in this example.
| Feature | What it does | Cogwell uses it for |
|---|---|---|
list_display | Columns on the list page | Bookings by date, workshop and mechanic |
list_filter | Filters beside the list | Job cards by status and workshop |
show_facets (5.0) | Counts next to each filter option | "Ready (4)" at a glance |
search_fields | The search box, with ^, = and @ prefixes | Customers by name, bikes by frame number |
date_hierarchy | Year, month and day links | Bookings for one day |
list_select_related | Joins related tables in one query | Avoids one query per row on every list |
readonly_fields | Shows values that cannot be edited | Photos, timestamps, invoice totals |
| Inlines | Related rows inside a form | Parts used on a job card |
autocomplete_fields | A search box for a related record | 2,400 parts, 9,000 customers |
| Actions | A command applied to selected rows | "Mark selected as ready" |
| Permissions and groups | Who may view, add, change or delete | Managers versus head office |
| Template overrides | Change a page's layout or add links | A link to the reorder report |
| Custom admin views | Your own page inside the admin frame | The nightly reorder report |
Actions, and the trap hidden in bulk changes
An action is a command that runs on every row a user has ticked in the list. Django ships one, "delete selected objects", and you can add your own. An action is a function that receives the ModelAdmin, the request and a QuerySet of the selected rows. The @admin.action decorator gives it a description and, optionally, the permissions a user needs to see it5.
The trap is in how the documentation's own first example works: it calls queryset.update(...). That is efficient, and it is a single SQL UPDATE. The QuerySet reference is explicit that update() does not call any save() methods on your models and does not send the pre_save or post_save signals6. Bulk delete has a similar caveat: the built in delete action uses QuerySet.delete(), so your model's own delete() method is not called5, although the delete signals are still sent6.
Why does that matter? Because many projects put side effects in save() or in a signal: send the "your bike is ready" message, write an audit entry, adjust stock. A bulk action that uses update() silently skips all of them.
Example: the "mark as ready" action that told nobody
Owen's first version of the action looked like the documentation:
# repairs/admin.py: the first version (do not copy)
@admin.action(description="Mark selected job cards as ready")
def mark_ready(modeladmin, request, queryset):
queryset.update(status=JobCard.Status.READY)
The "your bike is ready" email and SMS were sent by a post_save signal on JobCard. On a busy Saturday morning, when 30% of the week's online bookings land between Friday 6pm and Saturday noon, a manager ticked eight finished bikes and ran the action. Eight cards turned "ready". Eight customers heard nothing and did not come.
The fix is a rule, not a patch: every side effect lives in one service function, and every screen calls it. The admin, the workshop board and the future mobile app all change status the same way.
# repairs/services.py
from django.db import transaction
from .models import JobCard
from .notifications import notify_bike_ready
def mark_ready(job_card):
"""The one place a job card becomes ready. Every screen calls this."""
with transaction.atomic():
job_card.status = JobCard.Status.READY
job_card.save(update_fields=["status", "updated_at"])
# Send only after the database has committed the change
transaction.on_commit(lambda: notify_bike_ready(job_card))
# repairs/admin.py: the action, calling the service
from . import services
@admin.register(JobCard)
class JobCardAdmin(admin.ModelAdmin):
# ... the options shown earlier ...
actions = ["mark_selected_ready"]
@admin.action(description="Mark selected as ready (emails and texts the customer)")
def mark_selected_ready(self, request, queryset):
cards = list(queryset.filter(status=JobCard.Status.IN_REPAIR))
for card in cards:
services.mark_ready(card)
self.message_user(request, f"{len(cards)} job cards marked ready.")
Two details are deliberate. The action only touches cards that are in repair, so a slip of the mouse cannot mark a bike as ready that nobody has touched. And the description tells the manager that customers will be contacted, because a button that sends 8 text messages should say so.
The same thinking applies to stock. If the custom parts screen lowers in_stock when a part is used, but a manager adds a PartUsage row through the admin inline, stock drifts and the nightly reorder report lies. Put the stock change in a service function, and call it from the admin's save_formset() as well.
Permissions and groups: who may see what
Django's permission system is built into the same django.contrib.auth app that handles logins. For every model, migrate creates four permissions: add, change, delete and view7. The view permission arrived in Django 2.1 in August 2018, so read only admin access has been available for years8. A group bundles permissions, and a user in a group has all of its permissions7.
The admin honours these permissions on every page. Viewing needs view or change, the add form needs add, editing needs change, deleting needs delete7. Two warnings in the documentation deserve to be repeated. Logging in to the admin at all requires is_staff2. And giving someone who is not a superuser the right to edit users is, in practice, the same as making them a superuser, because they can raise their own permissions7.
What the permission system does not do is restrict rows. Django's permissions are per model: a manager either may change bookings or may not. "Only bookings at my own workshop" is a row level rule, and you write it yourself.
Example: six managers, six workshops, one admin
First the roles, created by a management command rather than a data migration. The documentation explains why: default permissions are created by a handler that runs after migrate finishes7, so on a fresh database a data migration that looks them up can find nothing.
# accounts/management/commands/setup_roles.py
from django.contrib.auth.models import Group, Permission
from django.core.management.base import BaseCommand
ROLES = {
"Workshop managers": [
"view_booking", "change_booking",
"view_jobcard", "change_jobcard",
"view_customer", "change_customer",
"view_bike", "change_bike",
"view_part", "change_part",
"view_invoice",
],
"Head office": [
"view_booking", "view_jobcard", "view_customer", "view_bike",
"view_part", "change_part",
"view_invoice", "change_invoice",
"view_all_workshops", # a custom permission on Workshop
],
}
class Command(BaseCommand):
help = "Creates the back office groups and their permissions. Safe to run again."
def handle(self, *args, **options):
for name, codenames in ROLES.items():
group, _ = Group.objects.get_or_create(name=name)
permissions = Permission.objects.filter(codename__in=codenames)
group.permissions.set(permissions)
self.stdout.write(f"{name}: {permissions.count()} permissions")
The custom permission is declared on the model, so migrate creates it alongside the four defaults:
# workshops/models.py (excerpt)
class Workshop(models.Model):
name = models.CharField(max_length=100)
class Meta:
permissions = [("view_all_workshops", "Can see every workshop")]
Then a small base class does the row level scoping. In this example the custom user model from the start chapter carries a workshop field for managers.
# workshops/admin_mixins.py
from django.contrib import admin
from .models import Workshop
class WorkshopScopedAdmin(admin.ModelAdmin):
"""Managers see only their own workshop. Head office sees all six."""
workshop_lookup = "workshop" # subclasses set the path, e.g. "booking__workshop"
def get_queryset(self, request):
qs = super().get_queryset(request)
if request.user.has_perm("workshops.view_all_workshops"):
return qs
# No workshop on the user means no rows: the safe default
return qs.filter(**{self.workshop_lookup: request.user.workshop_id})
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "workshop" and not request.user.has_perm(
"workshops.view_all_workshops"
):
kwargs["queryset"] = Workshop.objects.filter(pk=request.user.workshop_id)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
BookingAdmin now inherits from WorkshopScopedAdmin, and JobCardAdmin does the same with workshop_lookup = "booking__workshop". Because the admin loads a single record through get_queryset() as well, a manager who types another workshop's booking number into the address bar gets "does not exist", not someone else's customer.
The scoping is code that protects personal data, so it gets tests. The pattern is simple: create two workshops, a manager for one, and assert that the other workshop's booking is absent from the list and returns a redirect or not found on its change page. The testing series later in this programme covers how to write those tests first.
Changing how the admin looks
The admin's look can be adjusted at three levels.
Site wide text. AdminSite.site_header and site_title replace "Django administration" at the top and in the browser tab2.
Templates. Most admin pages can be overridden per app or per model: create templates/admin/<app>/<model>/ in your project and put a template there that extends the original. The documentation lists the templates that can be overridden this way, among them change_form.html and change_list.html2.
Custom views inside the admin. ModelAdmin.get_urls() adds your own pages, and if they extend admin/base_site.html they look like part of the admin2. This is the right home for a report.
Themes. Several maintained third party packages restyle the whole admin. Grappelli has been around since 20109. Jazzmin, from 2020, builds on AdminLTE 3 and Bootstrap10. Unfold, first released in 2022, is the youngest of the four, with a modern look and active development11. Django Admin Interface adds themes you configure from the admin itself12. They are on PyPI as django-grappelli, django-jazzmin, django-unfold and django-admin-interface. All of them change how the admin looks, none of them changes what it is: a generic editor for records. Choose one for readability if your managers spend hours a day in it, check it supports your Django version before every upgrade, and expect each theme to add one more thing to update.
Example: the reorder report inside the admin
The nightly reorder report is a record shaped job: a list of parts at or below their reorder level, per workshop. It belongs in the admin, as a custom view on PartAdmin:
# parts/admin.py (extended)
from django.db.models import F
from django.template.response import TemplateResponse
from django.urls import path
@admin.register(Part)
class PartAdmin(admin.ModelAdmin):
# ... the options shown earlier ...
def get_urls(self):
custom = [
path(
"reorder-report/",
self.admin_site.admin_view(self.reorder_report), # login and staff check
name="parts_part_reorder_report",
),
]
return custom + super().get_urls() # custom first, or the catch all wins
def reorder_report(self, request):
parts = self.get_queryset(request).filter(in_stock__lte=F("reorder_level"))
context = {
**self.admin_site.each_context(request), # header, sidebar, user menu
"title": "Reorder report",
"parts": parts.order_by("sku"),
}
return TemplateResponse(request, "admin/parts/reorder_report.html", context)
{# templates/admin/parts/reorder_report.html #}
{% extends "admin/base_site.html" %}
{% block content %}
<table>
<thead><tr><th scope="col">SKU</th><th scope="col">Part</th><th scope="col">In stock</th><th scope="col">Reorder at</th></tr></thead>
<tbody>
{% for part in parts %}
<tr><td>{{ part.sku }}</td><td>{{ part.name }}</td><td>{{ part.in_stock }}</td><td>{{ part.reorder_level }}</td></tr>
{% empty %}
<tr><td colspan="4">Nothing to reorder today.</td></tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
admin_view() wraps the page in the admin's own login and staff check, and each_context() gives it the admin's header and navigation. Because the view starts from self.get_queryset(request), the workshop scoping from the previous section applies to the report too. A link to it goes into an override of templates/admin/parts/part/change_list.html, and managers find the report one click from the parts list.
Keeping the admin fast on big tables
The admin is fast on small tables without any effort, and slow on big tables without some. Five settings decide most of it, and every one is in the reference documentation2:
list_select_related. Without it, a column that shows a related record can run one extra query per row. With it, the list runs one query with joins. Whenlist_displaycontains a foreign key, Django already applies a basicselect_related(), but a column that follows two relations, such as the customer behind a booking, needs it spelled out.show_full_result_count. By default a filtered list shows "99 results (103 total)", and the total is a full count of the table, which the documentation calls expensive on tables with many rows. Set it toFalseand the page shows "Show all" instead.show_facets. As above: one count query per filter. Switch it off where it hurts.search_fields. The default lookup is a case insensitive "contains", which cannot use an ordinary index. The documentation suggests your ownget_search_results()with full text search for very large tables, and the^prefix ("starts with") or=prefix (exact match) can use an index where it fits.autocomplete_fieldsorraw_id_fields. Never let a form render a dropdown of every row in a big table.
Pagination defaults to 100 rows a page, and "show all" is capped at 200 rows by default2. Those defaults are sensible. Leave them.
Example: how big Cogwell's tables get
Priya estimated the row counts after two years at today's volume, to see which tables would need care. Bookings grow by about 1,150 a week, and each repair uses, in this example, about two parts on average. The yearly growth of a table is:
where is the number of new rows a year, is the number of bookings a week, is the number of rows each booking creates in that table and is the number of weeks in a year. For the reasoning behind multiplying rates like this, see Foundations: ratios and rates.
For bookings and job cards, one row each per booking:
Here and , so is 59,800 new rows a year.
For parts used, at two rows per booking:
So is about 60,000 rows a year and about 120,000, which after two years means roughly 120,000 bookings, 120,000 job cards and 240,000 part usages. None of that is large for PostgreSQL. The parts table stays at about 2,400 rows and customers near 9,000. The conclusion: list_select_related everywhere, autocomplete for parts and customers, and show_full_result_count = False on part usages. No other tuning is needed for years. Measuring beats guessing, and the ORM chapter shows how to count queries on a page.
Keeping the admin safe
The admin is a page that can read and change everything in your database, behind a username and a password. Treat it that way.
What Django does for you: only active users with is_staff can log in, every page checks permissions, the admin's forms are protected against cross site request forgery, and custom views wrapped in admin_view() get the same checks2. What it does not do in Django 5.0 is ask for a second factor at login.
The community advice is consistent. Jeff Triplett and Lacey Williams Henschel's list of ten tips for securing the admin recommends serving it over HTTPS, moving it away from /admin/, using two factor authentication and, for even more protection, a separate domain or a network that is not public13. Moving the URL is not real security on its own, but it removes the admin from the path of automated scanners that try /admin/ on every site, and it costs one line.
For two factor authentication, the django otp package (django-otp on PyPI) provides OTPAdminSite, an AdminSite subclass that only lets in users verified by a registered one time password device, such as an authenticator app14. The django two factor auth package (django-two-factor-auth) builds complete login flows on top of it15.
Example: Cogwell's admin, locked down
The admin site class, with two factor authentication and Cogwell's own header:
# cogwell/admin_site.py
from django_otp.admin import OTPAdminSite
class CogwellAdminSite(OTPAdminSite):
site_header = "Cogwell Cycles back office"
site_title = "Cogwell back office"
def __init__(self, name="admin"):
# Keep the usual "admin" name so every admin URL resolves as before
super().__init__(name)
Django's documented way to replace the default admin site is an AdminConfig subclass with default_site2:
# cogwell/apps.py
from django.contrib.admin.apps import AdminConfig
class CogwellAdminConfig(AdminConfig):
default_site = "cogwell.admin_site.CogwellAdminSite"
# cogwell/settings.py (excerpt)
INSTALLED_APPS = [
"cogwell.apps.CogwellAdminConfig", # replaces "django.contrib.admin"
"django.contrib.auth",
# ...
"django_otp",
"django_otp.plugins.otp_totp", # authenticator app codes
]
MIDDLEWARE = [
# ...
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django_otp.middleware.OTPMiddleware", # must come after authentication
# ...
]
# cogwell/urls.py
import os
from django.contrib import admin
from django.urls import path
# The path comes from the environment, so it is not in the public repository
ADMIN_PATH = os.environ.get("ADMIN_PATH", "admin")
urlpatterns = [
path(f"{ADMIN_PATH}/", admin.site.urls),
# ... the public site ...
]
Before switching on OTPAdminSite, Priya gave herself a backup code with the package's addstatictoken command, because the documentation warns that you can lock yourself out otherwise14. Then each of the eight admin users registered an authenticator app.
The last layer sits in front of Django. Cogwell's back office is only used from the six workshops and head office, so the web server only lets the admin path through from their addresses:
# Only the workshops' and head office's addresses reach the back office
location /backoffice-cw/ {
allow 203.0.113.0/24;
deny all;
proxy_pass http://cogwell_app;
}
The rest of Cogwell's security, from passwords to the deployment checklist, is the subject of the authentication and security chapter later in this series. The admin's part of it is this: eight people, scoped access, two factors, a non obvious path, and a network rule.
Where the admin breaks
Everything above makes the admin a very good back office. Here is where it stops, and why each limit follows from the design brief.
Complex workflows. The admin edits one record at a time, in forms shaped like your tables. A job that runs across several records in a fixed order (take in a bike, create a job card, assign a mechanic, add parts, mark ready, invoice, hand over) becomes a sequence of separate screens that the user has to remember. You can bend it with overridden templates, JavaScript and custom views, and every bend makes the next Django upgrade riskier.
Customers. The documentation says it in plain words: not for site visitors3. The admin's interface assumes someone who understands your data model, and its permissions are per model, not per person's own data. A customer portal built on it would expose your structure and fight you on every screen.
Heavy custom user experience. Drag and drop, live updates, a layout built for a tablet in a workshop with greasy fingers: none of that is what a list of rows and a save button were designed for.
Large tables without care. Covered above. The admin is fast when you tell it what to fetch and slow when you do not.
Security if exposed carelessly. Covered above. A full database editor on the public internet with only a password in front of it is a risk you can avoid in an afternoon.
Example: the point where the workshop board needed its own page
During the spike, Owen tried the workshop board in the admin first, to see how far it would go. The job card list, filtered to one workshop, with status facets and a "mark as ready" action, works. A manager can run the workshop from it. Then Priya timed it.
To move one job card one step through the admin, a person opens the list, filters to their workshop, finds the card, opens it, changes the status and saves. Priya timed that at about 25 seconds. On a board page, one tap moves a card: about 4 seconds. Both timings are from the example's spike, not a general benchmark.
Each booking's job card moves three times: waiting to in repair, in repair to ready, ready to collected. So the hours spent on status changes each week are:
where is the hours per week spent moving cards, is the number of bookings a week, is the number of status changes per booking, is the seconds one change takes and converts seconds into hours. This is a rate multiplied out over a week, the same idea as in Foundations: ratios and rates.
Through the admin:
With seconds, is about 24.0 hours a week.
On the board:
With seconds, is about 3.8 hours a week.
The difference, , is about 20.1 hours a week of mechanics' and managers' time. At Cogwell's labour rate of £45 an hour, that is about £906 a week of workshop time spent clicking instead of repairing. And the cost is not spread evenly: it peaks on Saturday morning, exactly when 30% of the week's online bookings have just arrived.
The custom board took Owen about eight developer days in the plan (60 hours at 7.5 hours a day). At 20 hours saved a week, the board pays back its build time in about three weeks, and keeps paying every week after. That is where the record or task rule stops being a matter of taste. The board is built with templates and htmx in the next chapter of this series, the same board the Rails series builds with Hotwire.
The decision: admin or custom page
Put together, the rules make a short decision you can run on any back office screen. Who uses it first, then what shape the work has, then whether the screen has to be live.
Example: the decision run on Cogwell's screens
Run on the jobs from the table at the start:
- Customer corrections, bike lookups, stock adjustments, invoice lookups: staff, records, one model at a time, not live. The admin.
- The nightly reorder report: staff, records, but a list the standard pages cannot show. A custom view inside the admin.
- The workshop board: staff, but a task that crosses job cards, bookings and parts, and has to update live while six people use it. A custom page.
- Online booking: customers. A custom page, without a second thought.
What each route costs to build
A fair comparison has to include the cost on both sides. The admin is not free: you still write ModelAdmin classes, scoping, actions and tests. A custom page is not only a template: it needs views, forms, validation, permission checks, pagination and tests of its own.
Example: Priya's estimates for five screens
These are the example's planning estimates in developer days, made during the spike for this application. They are illustrative, not a benchmark, and they include tests.
The pattern is the point. For the four record shaped screens the admin costs 3.5 days against 15 days custom, less than a quarter. For the workshop board, the saving almost disappears (6 days against 8), and what the admin version produces is the 25 second click path from the previous section. The admin's advantage is large exactly where the work is record shaped, and close to nothing where it is not.
Rails has no built in admin: what Rails developers use instead
Since Cogwell chose Rails for the product, a fair comparison belongs here. Rails 7.1 has no admin interface. What it ships instead are generators: bin/rails generate scaffold creates a model, migration, controller, views and tests for one resource in a single command16. That gives you plain, editable CRUD pages in your own code, not a ready made back office.
For a back office, Rails developers add a gem. The most widely used, as of April 2024:
- ActiveAdmin (3.2.0, December 2023, MIT licence): a domain specific language in
app/adminthat describes lists, filters, forms and actions, built on the Arbre, Formtastic and Ransack gems. The closest in spirit to Django's admin17. - Administrate (0.20.1, January 2024, MIT licence), from thoughtbot: generates dashboards and plain Rails controllers and views you can override, with the stated aim of staying as close to standard Rails as possible. Still before version 1.018.
- Avo (version 3, April 2024): built on Hotwire, with a free, open source community edition and paid Pro and Advanced editions per application for features such as dashboards and advanced authorisation19.
- Trestle (0.9.8, April 2023, LGPL licence): a responsive admin framework configured in Ruby blocks20.
- RailsAdmin (3.1.2, March 2023, MIT licence): a Rails engine that generates an interface for managing your data with little configuration21.
The honest comparison: Django's admin is part of the framework, maintained by the same people, documented in the same place and upgraded in the same release. That is a real advantage, and over five years it is the biggest one, because a third party admin gem is one more dependency that has to keep pace with every Rails upgrade. On the other side, the Rails options differ in philosophy, so a Rails team can choose between a configured DSL (ActiveAdmin), generated code it owns (Administrate) or a commercial product with support (Avo). The Rails series covers how to judge a gem before adding it, in the chapter on building Rails applications efficiently.
Example: the same back office in the Rails version
In the Rails version of the spike, Owen tried Administrate for the same record shaped screens: customers, bikes, parts and invoices. Generating the dashboards took about the same time as the Django admin. Scoping each manager to a workshop took a little longer, because it is written in plain Rails controllers rather than a get_queryset() hook, and the authorisation pattern from the Rails security chapter carried over directly. The workshop board was a custom page in both versions. The admin question had the same answer in both frameworks: records in the generated tool, tasks in your own pages.
My view: what an admin is worth to a small business
I build on Ruby on Rails, so take this as the view of someone who does not get Django's admin for free, and has looked at it with some envy.
My view: for a small business, a good admin is worth more in the first year than almost any feature on the roadmap, because it turns every data problem from a developer's job into a manager's job. Hannah's managers can fix a typo, correct stock or find an invoice without asking Priya. That is hours of developer time a week, and it is a calmer business. The Django admin delivers that on the first day, and it is the strongest single argument for Django in a back office heavy product.
It is worth less than it looks in three cases, and these are my judgement, not the documentation's:
- when the business's core work is a workflow (a booking system, a repair shop floor, a warehouse), because the core screens will be custom anyway,
- when the people doing the work are not office staff,
- when a team keeps bending the admin into a product, because each override is a small debt paid at every upgrade.
The pattern I recommend, in either framework: the admin is the spare key, never the front door. Give trusted staff the generated back office for records, build your own pages for tasks, put every side effect in a service function both of them call, and keep the admin as the place to correct data even after the custom pages exist. When the custom board has a bug on a Saturday morning, a manager can still fix a job card in the admin. A spare key is worth a great deal precisely because you rarely need it.
For the person paying for this
If you are commissioning a Django application, the admin is good news for your budget, and a few questions keep it that way.
- Ask which screens are in the admin and which are custom, and why. A good answer sorts them by who uses them and what shape the work has, much like the table at the top of this chapter.
- Ask who has an admin login. It should be a short list of trusted staff, each with only the permissions they need. "Everyone is a superuser" is a warning sign.
- Ask how the admin is protected. Expect two factor authentication, a path other than
/admin/, and ideally a network restriction. - Ask where the side effects live. Emails, texts, stock changes and audit entries should happen the same way whether a change comes from the admin or from a custom page.
- Be wary of a customer facing portal built on the admin. The documentation itself says it is not meant for that.
If you would like a second pair of eyes on a back office plan, in Django or Rails, the free workshop is the place to start, and my prices are published so you know what building the custom parts would cost.
Conclusion
The Django admin is a generated back office for trusted staff, and the documentation is clear that it is meant to stay one. Used for what it is, it is remarkable: a few dozen lines of ModelAdmin configuration give managers lists, filters with facet counts, search, inlines, autocomplete, actions, permissions and a change history, on the first afternoon of a project.
The rule that tells you where it stops is simple. People who come to change a record belong in the admin. People who come to finish a task, people who are not staff, and screens that must change live belong on pages you build. At Cogwell that put six of nine back office jobs in the admin and the workshop board on its own page, where about 20 hours a week of clicking came back to the workshop floor.
Keep the side effects in service functions, scope every manager's rows, protect the login with a second factor, and keep the admin as the spare key long after the custom pages arrive.
