Django 6.1.3

2.2 Booting Django

The Apps registry and three phases

How does Apps.populate load every installed app, import every models module, and fire every ready hook without circular-import deadlocks?

At import time, django/apps/registry.py instantiates one global registry: apps = Apps(installed_apps=None). Passing installed_apps=None is reserved strictly for that singleton — Apps.__init__ explicitly raises RuntimeError if any second caller omits an app list, forcing isolated registries such as migration StateApps to supply their apps and populate immediately.

Lock-guarded, idempotent, and strictly non-reentrant

Apps.populate moves three boolean flags forward in one direction only: Apps.apps_ready, Apps.models_ready, and Apps.ready.

Calling populate on an already-booted process returns immediately on line 69 (if self.ready: return) without touching any lock, making repeated calls to django.setup() cheap and safe. On a cold boot, however, multi-threaded WSGI servers can spawn worker threads that race into initialization simultaneously, so populate acquires Apps._lock (a threading.RLock) and re-checks Apps.ready inside the lock.

Using a threading.RLock protects against other threads, yet allows the same thread to re-enter the lock if an imported module or ready() hook accidentally calls django.setup() again while startup is still underway. That is why line 80 checks Apps.loading: if loading is already True, Django aborts immediately rather than running AppConfig.ready hooks twice.

Recorded on Django 6.1.3 ch02-startup script
Controlled startup failures before and during django.setup()
...
  TRAP re-entrant django.setup() inside ready() -> RuntimeError: populate() isn't reentrant

Watching all three phases boot desk

Running django.setup() against our newsroom project traces every phase transition across all 8 installed apps.

Recorded on Django 6.1.3 ch02-startup script
django.setup() three-phase startup on desk/
  before setup: apps_ready=False  models_ready=False  ready=False
  configure_logging('logging.config.dictConfig')
  set_script_prefix('/')
  Apps.populate(8 installed apps)
    Phase 1: AppConfig.create('django.contrib.admin')
    Phase 1: AppConfig.create('django.contrib.auth')
    Phase 1: AppConfig.create('django.contrib.contenttypes')
    Phase 1: AppConfig.create('django.contrib.sessions')
    Phase 1: AppConfig.create('django.contrib.messages')
    Phase 1: AppConfig.create('django.contrib.staticfiles')
    Phase 1: AppConfig.create('newsroom.apps.NewsroomConfig')
    Phase 1: AppConfig.create('subscribers.apps.SubscribersConfig')
    Phase 2: AdminConfig.import_models()  [label='admin']
      Apps.register_model('contenttypes', ContentType)
      Apps.lazy_model_operation(admin.logentry, auth.user)
      Apps.lazy_model_operation(admin.logentry, contenttypes.contenttype)
      Apps.register_model('admin', LogEntry)
...
    Phase 2: ContentTypesConfig.import_models()  [label='contenttypes']
...
    Phase 2: NewsroomConfig.import_models()  [label='newsroom']
      Apps.register_model('newsroom', Desk)
...
      Apps.register_model('newsroom', PublishedStory)
    Phase 2: SubscribersConfig.import_models()  [label='subscribers']
      Apps.lazy_model_operation(subscribers.subscription, newsroom.desk)
      Apps.register_model('subscribers', Subscription)
      Apps.lazy_model_operation(newsroom.desk)
    Phase 3: AdminConfig.ready()  [label='admin']
    Phase 3: AuthConfig.ready()  [label='auth']
    Phase 3: ContentTypesConfig.ready()  [label='contenttypes']
    Phase 3: SessionsConfig.ready()  [label='sessions']
    Phase 3: MessagesConfig.ready()  [label='messages']
    Phase 3: StaticFilesConfig.ready()  [label='staticfiles']
    Phase 3: NewsroomConfig.ready()  [label='newsroom']
    Phase 3: SubscribersConfig.ready()  [label='subscribers']
  after setup: apps_ready=True  models_ready=True  ready=True  app_configs=8  models=15

Phase 1: Discovering AppConfig without touching models

For every entry in INSTALLED_APPS, AppConfig.create attempts importlib.import_module first. When the entry names a package such as "django.contrib.admin", Django looks for an apps submodule containing a single AppConfig subclass (ignoring subclasses marked default = False). If the module defines multiple subclasses — as django/contrib/admin/apps.py does with SimpleAdminConfig and AdminConfig — Django picks the sole class declaring default = True. Projects that want to disable automatic admin.py discovery simply list "django.contrib.admin.apps.SimpleAdminConfig" directly, taking the fallback branch in AppConfig.create that loads a class via import_string and then imports the module named by AppConfig.name.

Each constructed AppConfig is stored in Apps.app_configs keyed by its unique label. Apps.populate rejects both duplicate labels and duplicate module names with ImproperlyConfigured, attaches app_config.apps = self, and flips Apps.apps_ready to True. In our cold-boot benchmark, Phase 1 takes 71.21 ms (22.8% of django.setup). Crucially, not a single models.py file has been imported yet — which is why placing a model import at the top of an app’s __init__.py or apps.py crashes Phase 1 immediately.

Phase 2: Import order is not registration order

Once Apps.apps_ready is True, Apps.populate loops over Apps.app_configs in INSTALLED_APPS order and calls AppConfig.import_models. Each config binds AppConfig.models to its bucket inside Apps.all_models (a collections.defaultdict of dicts) and imports <app>.models if that submodule exists. Executing each Model class body runs ModelBase.__new__, which registers the class via Apps.register_model.

You might expect each app’s AppConfig.import_models call to register only its own models. Recording which import_models call actually triggers each Apps.register_model call on our newsroom project reveals a sharper reality:

Recorded on Django 6.1.3 ch02-startup script
Phase 2 import-trigger vs. model-registration matrix on desk/
  importer_app    registered_models (app_label:ModelName)
  admin            2  contenttypes:ContentType  admin:LogEntry
  auth             6  auth:Permission,Group_permissions,Group,User_groups,User_user_permissions,User
  contenttypes     0  (none)
  sessions         1  sessions:Session
  messages         0  (none)
  staticfiles      0  (none)
  newsroom         8  newsroom:Desk,Reporter,Beat,Edition,Story,StoryBeat,Correction,PublishedStory
  subscribers      1  subscribers:Subscription
Figure 2.3 Phase 2 registration matrix parsed directly from ch02-startup. Look at row 1 and row 3: AdminConfig registers ContentType two slots ahead of ContentTypesConfig, leaving step 3 with zero new registrations.

That off-diagonal jump happens because django/contrib/admin/models.py executes from django.contrib.contenttypes.models import ContentType at module top level. Python imports django.contrib.contenttypes.models immediately, ModelBase.__new__ finds ContentTypesConfig (already created in Phase 1!) and drops ContentType into Apps.all_models under "contenttypes". Two iterations later, when ContentTypesConfig runs AppConfig.import_models, Python returns the cached module from sys.modules and AppConfig.models simply points at the bucket that already holds ContentType.

Also count the row for auth: 6 calls to Apps.register_model for three declared models (Permission, django.contrib.auth.models.Group, User). The other three ("Group_permissions", "User_groups", and "User_user_permissions") are the implicit intermediate join models Django generates for ManyToManyField declarations without an explicit through model. Across all eight apps, Phase 2 takes 73.74 ms (23.6% of django.setup), calls Apps.clear_cache, and flips Apps.models_ready to True.

Phase 3: Running every AppConfig.ready hook

With both Apps.apps_ready and Apps.models_ready flipped to True, Apps.populate iterates Apps.get_app_configs in INSTALLED_APPS order and invokes AppConfig.ready on every app. Now it is safe to import models, connect signal receivers, register system checks, and run AdminConfig.ready’s autodiscover. On our newsroom project, all eight ready() hooks finish in 14.05 ms (4.5% of startup). Django flips Apps.ready to True and signals Apps.ready_event so the development autoreloader knows the process booted cleanly.

Every guard in those three phases defends one invariant: never define a model before Phase 1 completes, and never rely on all models existing before Phase 2 completes. Next we trigger the exact failures that fire when code breaks that order — and watch how Django wires cross-app foreign keys when two apps load in reverse order.