---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# AdminSite, autodiscover, and dynamic URLs

How does `django.contrib.admin.autodiscover` find every `admin.py` at startup, and how does `AdminSite.get_urls` synthesize URL routes for every registered model?

Nothing in `django.contrib.admin` 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/", admin.site.urls)` in `"desk/urls.py"`. What makes it feel magical is a three-step startup sequence: `AdminConfig.ready` discovers every `"admin.py"`, `AdminSite.register` instantiates a long-lived `ModelAdmin` per model, and `AdminSite.get_urls` 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.ready` (`django/contrib/admin/apps.py:AdminConfig.ready`):

1. It registers Admin system checks (`check_dependencies` and `check_admin_app`, verifying that `AuthenticationMiddleware`, `SessionMiddleware`, `MessageMiddleware`, and `DjangoTemplates` are configured).
2. It calls `autodiscover` (`django/contrib/admin/__init__.py:autodiscover`), which is a one-liner: `autodiscover_modules("admin", register_to=site)`. (If you prefer explicit imports without automatic discovery, swap `"django.contrib.admin"` for `SimpleAdminConfig` (`django/contrib/admin/apps.py:SimpleAdminConfig`).)
3. `autodiscover_modules` (`django/utils/module_loading.py:autodiscover_modules`) iterates every installed `AppConfig`, 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 an `ImportError` on line 30, Django restores `"site._registry"` to its pre-import state rather than leaving half-registered models behind!

When `"desk/"`'s `"newsroom/admin.py"` executes `"@admin.register(Story)"` via `register` (`django/contrib/admin/decorators.py:register`), it calls **`AdminSite.register`** (`django/contrib/admin/sites.py:AdminSite.register`). Look at lines 113–149 of `django/contrib/admin/sites.py`:

- It refuses abstract models AND (in Django `6.1`) models with composite primary keys (`"model._meta.is_composite_pk"`), raising `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 `ModelAdmin` (`django/contrib/admin/options.py:ModelAdmin`) **once at startup** and stores it in `"self._registry[model] = admin_class(model, self)"`! That is a critical thread-safety rule: your `"StoryAdmin"` instance is **shared across every thread and every request for the lifetime of the worker process** — never assign per-request state like `"self.current_user = request.user"` onto a `ModelAdmin`!

## Synthesizing URLs and the `AdminSite.admin_view` wrapper

When `"desk/urls.py"` mounts `"admin.site.urls"` via `AdminSite.urls` (`django/contrib/admin/sites.py:AdminSite.urls`), it returns the 3-tuple `(self.get_urls(), "admin", self.name)` — giving the Admin its `"admin"` URL namespace and instance name!

Open `AdminSite.get_urls` (`django/contrib/admin/sites.py:AdminSite.get_urls`) and `ModelAdmin.get_urls` (`django/contrib/admin/options.py:ModelAdmin.get_urls`):

1. **Site-wide routes:** `""` (`index`), `"login/"`, `"logout/"`, `"password_change/"`, `"autocomplete/"`, `"jsi18n/"`, and `"r/<content_type_id>/<object_id>/"` (`view_on_site`).
2. **Per-model routes:** Loops over `"self._registry.items()"` and mounts `path("<app_label>/<model_name>/", include(model_admin.urls))`. For every registered model (like `"newsroom.story"`), `ModelAdmin.get_urls` emits five named routes — `"newsroom_story_changelist"`, `"newsroom_story_add"`, `"newsroom_story_history"`, `"newsroom_story_delete"`, `"newsroom_story_change"` — plus a legacy `"<object_id>/"` redirect!
3. **App index & catch-all:** Appends an `app_index` regex matching registered app labels plus `final_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.admin_view`** (`django/contrib/admin/sites.py:AdminSite.admin_view`), which layers three protections automatically:

- **Staff gate (`AdminSite.has_permission`, `django/contrib/admin/sites.py:AdminSite.has_permission`):** Requires `request.user.is_active and request.user.is_staff`; everyone else gets a `302` redirect to `"admin:login"` with `"?next=..."`.
- **Cache suppression (`never_cache`, `django/views/decorators/cache.py:never_cache`):** Unless `cacheable=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`, `django/views/decorators/csrf.py:csrf_protect`):** Enforces CSRF validation even if a project omitted `CsrfViewMiddleware` globally.

Watch all eight registered models on `"desk/"`, `"StoryAdmin"`'s synthesized URL names, and `admin_view` redirecting anonymous requests while marking staff responses uncacheable live:

```text recording=ch11-auth
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 /admin/newsroom/story/"` has cleared `AdminSite.admin_view` and routed to `ModelAdmin.changelist_view`, 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](changelist.md).
