11.5 Sessions, auth, and the admin
AdminSite, autodiscover, and dynamic URLs
How does django find every admin.py at startup, and how does AdminSite synthesize URL routes for every registered model?
Nothing in django is special-cased inside Django’s request handler. The Admin is simply an ordinary Django app registered in "INSTALLED_APPS" and mounted at path("admin/ in "desk/urls.py". What makes it feel magical is a three-step startup sequence: AdminConfig discovers every "admin.py", AdminSite instantiates a long-lived ModelAdmin per model, and AdminSite synthesizes an entire nested URL tree wrapped in authentication, CSRF, and cache-control guards.
AdminConfig.ready , autodiscover, and AdminSite.register
When Django boots (Chapter 2), AppConfig.ready runs across every installed app. Open AdminConfig:
- It registers Admin system checks (
check_dependenciesandcheck_admin_app, verifying thatAuthenticationMiddleware,SessionMiddleware,MessageMiddleware, andDjangoTemplatesare configured). - It calls
autodiscover, which is a one-liner:autodiscover_modules("admin", register_to=site). (If you prefer explicit imports without automatic discovery, swap"djangofor.contrib .admin" SimpleAdminConfig.) autodiscover_modulesiterates every installedAppConfig, saves a shallow copy of"site._registry", and imports"<app>.admin". Saving the registry snapshot before each import is a quiet safeguard: if an app’s"admin.py"registers two models and then crashes with anImportErroron line 30, Django restores"site._registry"to its pre-import state rather than leaving half-registered models behind!
When "desk/"'s "newsroom/ executes "@admin via register, it calls AdminSite. Look at lines 113–149 of django/:
- It refuses abstract models AND (in Django
6.1) models with composite primary keys ("model), raising._meta .is_composite_pk" ImproperlyConfigured. - It refuses duplicate registrations (
AlreadyRegistered) and silently skips swapped models (like"auth.User"when"AUTH_USER_MODEL"points to a custom model). - Crucially, line 149 instantiates your
ModelAdminonce at startup and stores it in"self! That is a critical thread-safety rule: your._registry[model] = admin_class(model, self)" "StoryAdmin"instance is shared across every thread and every request for the lifetime of the worker process — never assign per-request state like"selfonto a.current_user = request .user" ModelAdmin!
Synthesizing URLs and the AdminSite.admin_view wrapper
When "desk/urls.py" mounts "admin via AdminSite.urls, it returns the 3-tuple (self — giving the Admin its "admin" URL namespace and instance name!
Open AdminSite and ModelAdmin:
- Site-wide routes:
""(index),"login/","logout/","password_change/," "autocomplete/","jsi18n/", and"r/(<content_type_id>/ <object_id>/ " view_on_site). - Per-model routes: Loops over
"selfand mounts._registry .items()" path("<app_label>/. For every registered model (like<model_name>/ ", include(model_admin .urls)) "newsroom.story"),ModelAdminemits five named routes —.get_urls "newsroom_story_changelist","newsroom_story_add","newsroom_story_history","newsroom_story_delete","newsroom_story_change"— plus a legacy"<object_id>/"redirect! - App index & catch-all: Appends an
app_indexregex matching registered app labels plusfinal_catch_all_view(which turns mistyped admin URLs into clean redirects when logged in — or redirects anonymous probes to login so attackers cannot probe which admin paths exist!).
Every view in that tree (except "login/") is wrapped by AdminSite, which layers three protections automatically:
- Staff gate (
AdminSite,.has_permission AdminSite): Requires.has_permission request; everyone else gets a.user .is_active and request .user .is_staff 302redirect to"admin:login"with"?next=...". - Cache suppression (
never_cache,never_cache): Unlesscacheable=True(used only for"jsi18n/"and password-change templates), stamps"Cache-Control: max-age=0, no-cache, no-store, must-revalidate, private"so sensitive admin HTML is never cached by shared proxies or back-button caches. - CSRF protection (
csrf_protect,csrf_protect): Enforces CSRF validation even if a project omittedCsrfViewMiddlewareglobally.
Watch all eight registered models on "desk/", "StoryAdmin"'s synthesized URL names, and admin_view redirecting anonymous requests while marking staff responses uncacheable live:
5. AdminSite registry, dynamic URLs, and admin_view
registered_models (8) = ['auth.group', 'auth.user', 'newsroom.beat', 'newsroom.desk', 'newsroom.edition', 'newsroom.reporter', 'newsroom.story', 'subscribers.subscription']
story_admin_urls = ['newsroom_story_changelist', 'newsroom_story_add', 'newsroom_story_history', 'newsroom_story_delete', 'newsroom_story_change']
admin_view: anon_status=302 anon_redirect='/admin/login/?next=/admin/newsroom/story/' staff_status=200 cache_control='max-age=0, no-cache, no-store, must-revalidate, private'
Now that "GET / has cleared AdminSite and routed to ModelAdmin, we open the query engine behind every Admin table — and watch one innocent "list_display" method blow up from 5 queries to 80 — in Inside ChangeList: filters, search, and queries.