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

# AppConfig.ready and logging configuration

What runs inside `django.setup` before and after `Apps.populate`, and why can database queries inside `AppConfig.ready` corrupt migrations and tests?

Open `django/__init__.py` and the entire public boot function is seventeen lines long (`django/__init__.py:setup`). Ignoring its docstring, `django.setup` runs four local imports followed by three calls: `configure_logging`, optionally `set_script_prefix`, and `Apps.populate`.

Yet measuring those exact lines across five fresh Python subprocesses booting our newsroom project turns up a surprise that reading the code alone hides:

```text recording=ch02-bench
Cold django.setup() breakdown on desk/ (5 fresh Python subprocesses, milliseconds)
  stage                              median_ms   share
  import django.urls (setup line 16)    124.78    39.9%
  Settings.__init__ (desk.settings)       2.68     0.9%
  configure_logging (dictConfig)         24.12     7.7%
  Phase 1: AppConfig.create x 8          71.21    22.8%
  Phase 2: import_models x 8             73.74    23.6%
  Phase 3: AppConfig.ready x 8           14.05     4.5%
  Total django.setup()                  312.86   (least 306.46 ms)
```

Line 16 alone — `from django.urls import set_script_prefix` — accounts for **`124.78 milliseconds` (`39.9%`)** of the entire cold boot! Importing `django.urls` transitively loads `django.http`, `django.utils.translation`, `django.urls.resolvers`, and regular-expression helpers into `sys.modules` before Django has even opened `"desk.settings"`. That is why even an empty management command with zero installed apps still pays over a hundred milliseconds to run `django.setup()`.

## Why logging runs first — and the `DEFAULT_LOGGING` trap

Of the three runtime steps inside `django.setup`, `configure_logging` runs first (`django/utils/log.py:configure_logging`). Evaluating its first argument, `settings.LOGGING_CONFIG`, is ordinarily the exact expression that triggers `LazySettings._setup` on a cold boot (`2.68 ms`). Running logging before `Apps.populate` ensures that any warning or log record emitted while apps or models import already goes to the configured handlers.

Inside `configure_logging`, pay close attention to what happens when `LOGGING_CONFIG` is truthy (its default is `"logging.config.dictConfig"`): Django **always** applies `DEFAULT_LOGGING` first (`django/utils/log.py:DEFAULT_LOGGING`), wiring up the `"django"` and `"django.server"` loggers along with `RequireDebugTrue` (console output) and `RequireDebugFalse` (`AdminEmailHandler`, which emails `ADMINS` on unhandled HTTP 500 errors). Only *after* applying `DEFAULT_LOGGING` does Django invoke the configured callable with your own `settings.LOGGING` dictionary — spending `24.12 ms` on our newsroom boot.

> **Trap.** Python's standard `logging.config.dictConfig` defaults `"disable_existing_loggers"` to `True`. If you write a custom `LOGGING` dictionary and forget `"disable_existing_loggers": False`, `configure_logging` silently mutes every logger created before `django.setup()` ran — including loggers instantiated at import time by libraries imported inside `settings.py` itself. To bypass `DEFAULT_LOGGING` completely, set `LOGGING_CONFIG = None` and configure Python's `logging` module yourself.

## Why WSGI and ASGI pass `set_prefix=False`

Next, when `set_prefix=True` (the default), `django.setup` calls `set_script_prefix` with `"/"` or `settings.FORCE_SCRIPT_NAME`, storing that prefix inside an `asgiref.local.Local` container named `_prefixes` (`django/urls/base.py:set_script_prefix`, `django/urls/base.py:_prefixes`). Management commands, background workers, and one-off scripts never receive an HTTP request, so setting that ambient prefix once at boot lets `reverse` produce working URLs outside a request cycle.

Web entrypoints do the exact opposite. Both `get_wsgi_application` and `get_asgi_application` explicitly call `django.setup(set_prefix=False)` (`django/core/wsgi.py:get_wsgi_application`, `django/core/asgi.py:get_asgi_application`). Behind a reverse proxy or subpath mount, each incoming HTTP request carries its own `"SCRIPT_NAME"` (or `"root_path"` under ASGI), so `WSGIHandler.__call__` and `ASGIHandler.__call__` set the prefix per request rather than inheriting a process-wide startup default.

## What belongs — and what breaks — in `AppConfig.ready`

After Phases 1 and 2 finish, `Apps.populate` executes `AppConfig.ready` on every installed app in `INSTALLED_APPS` order (`django/apps/config.py:AppConfig.ready`). Across all eight apps in our newsroom project — including `AdminConfig.ready` registering admin system checks and running `autodiscover`, and our newsroom app importing its signals module to connect `post_save` with a fixed `"dispatch_uid"` — Phase 3 takes just `14.05 ms`.

Good `ready()` work is strictly in-memory and idempotent: connecting signals, registering custom checks with `CheckRegistry`, or discovering plugin modules across installed apps.

What breaks projects is putting **database queries** inside `AppConfig.ready`. Every Django command calls `django.setup()` before doing its own job — `manage.py check`, `manage.py makemigrations`, `manage.py migrate`, `manage.py test`, and every production worker boot. Watch what Django `6.1.3` actually does when a `ready()` hook tries to count stories against a fresh database before `migrate` can run:

```text recording=ch02-startup
Controlled startup failures before and during django.setup()
...
  TRAP Story.objects.count() inside ready() before migrate -> RuntimeWarning: Accessing the database during app initialization is discouraged. To fix this warning, avoid executing queries in AppConfig.ready() or when your app modules are imported.
  TRAP Story.objects.count() inside ready() before migrate -> OperationalError: no such table: newsroom_story
```

Django fires *both* barrels. First, `CursorDebugWrapper` / `CursorWrapper` catches the query while `Apps.ready` is still `False` and emits a `RuntimeWarning` (`django/db/backends/utils.py:CursorWrapper`). Then SQLite immediately crashes with `OperationalError: no such table: newsroom_story` — locking you out of running `manage.py migrate` to create the table in the first place!

> **Trap.** Even when the tables already exist, querying the database inside `AppConfig.ready` causes three quieter bugs: during `manage.py test`, `ready()` runs against the *configured* database before `DiscoverRunner` creates the isolated test database; under the development *runserver*, `ready()` executes *twice* (once in the reloader supervisor process, once in the child worker); and under a preloading WSGI server such as Gunicorn with preloading enabled, opening a database connection inside `ready()` shares one open socket file descriptor across every forked child process until queries corrupt one another on the wire.

Once `django.setup()` returns, settings are loaded and the app registry is live. That leaves one last startup mystery: what happens when code tries to change a setting *after* boot?
