# Django Internals > How Django works from the inside: the hidden machinery underneath the framework's promises, verified against Django 6.1.3 and measured on one running application. Describes Django 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a): every backticked name exists in Django's source at the pinned commit, and every `path:Symbol` pointer resolves by AST to its exact lines. Every link below points to the page's markdown twin; drop `.md` for the rendered HTML. Data index: https://djangointernals.dev/index.json. Reverse symbol index: https://djangointernals.dev/names.json. ## 1. One request, unwrapped - [One request, unwrapped](https://djangointernals.dev/introduction.md): Follow a single HTTP request through Django from WSGI entry to SQL and HTML, and see the framework's core design bets in action. - [One request from wire to HTML](https://djangointernals.dev/introduction/one-request.md): What actually wakes up inside Django between a web server handing over a request dictionary and receiving back HTML bytes? - [Django's design bets](https://djangointernals.dev/introduction/design-bets.md): Why is Django built the way it is — batteries included, synchronous at its core, explicit about queries, and hostile to global object caches? - [The newsroom and the method](https://djangointernals.dev/introduction/the-desk.md): Meet the single Django 6.1.3 application this book measures, and see how live recordings, AST source pointers, and plates work. ## 2. Booting Django - [Booting Django](https://djangointernals.dev/startup.md): Lazy configuration, the two-phase app registry, and why import order decides whether a project starts cleanly or crashes before the first request. - [Lazy settings and configuration](https://djangointernals.dev/startup/lazy-settings.md): How does `LazySettings` stay unconfigured at import time, merge project values over defaults, and become an ordinary object on first attribute read? - [The Apps registry and three phases](https://djangointernals.dev/startup/apps-registry.md): How does `Apps.populate` load every installed app, import every models module, and fire every `ready` hook without circular-import deadlocks? - [Why import order breaks startup](https://djangointernals.dev/startup/import-order.md): What triggers `AppRegistryNotReady`, and how does Django defer cross-app model references until every model class exists? - [AppConfig.ready and logging configuration](https://djangointernals.dev/startup/ready-hook.md): What runs inside `django.setup` before and after `Apps.populate`, and why can database queries inside `AppConfig.ready` corrupt migrations and tests? - [Mutating settings at runtime and in tests](https://djangointernals.dev/startup/overrides.md): Why does assigning to a setting leave some Django subsystems holding stale values, and how does `override_settings` notify the rest of the framework? ## 3. Handlers, middleware, and async - [Handlers, middleware, and async](https://djangointernals.dev/handlers.md): A `WSGIHandler` or `ASGIHandler` turns a flat list of middleware strings into a nested chain of callables around the view, trapping exceptions at every layer and bridging sync and async across threads. - [WSGI and ASGI entry points](https://djangointernals.dev/handlers/entry-points.md): How do `WSGIHandler` and `ASGIHandler` turn a server's raw environment dictionary or ASGI scope into a Django request and stream the response back? - [Building the middleware onion](https://djangointernals.dev/handlers/the-onion.md): How does `BaseHandler.load_middleware` turn `settings.MIDDLEWARE` into a single nested callable, and why does order invert on the way out? - [MiddlewareMixin and short-circuits](https://djangointernals.dev/handlers/hooks.md): How do `process_request`, `process_view`, `process_template_response`, and `process_response` fit into modern callable middleware, and what skips when a layer returns early? - [Exception walls and error responses](https://djangointernals.dev/handlers/exceptions.md): Why does an exception raised inside a view become a 404 or 500 response before outer middleware ever sees it? - [Sync and async inside one chain](https://djangointernals.dev/handlers/async-bridge.md): How does Django run a synchronous middleware beside an asynchronous view inside one ASGI request without deadlocking the event loop? - [Measuring the thread-pool crossing](https://djangointernals.dev/handlers/crossing-cost.md): How much latency do sync/async mode switches actually add under ASGI, and how many crossings does a default Django middleware stack trigger? ## 4. HTTP, routing, and views - [HTTP, routing, and views](https://djangointernals.dev/routing.md): How Django parses requests and streams responses, compiles URL patterns into regular expressions, reverses them back into paths, and dispatches function and class-based views. - [Building HttpRequest and QueryDict](https://djangointernals.dev/routing/request-object.md): How do `WSGIRequest` and `ASGIRequest` decode headers, cookies, and query strings lazily, and why is `QueryDict` immutable by default? - [File uploads and streaming responses](https://djangointernals.dev/routing/uploads-and-streaming.md): How does Django stream multipart uploads without exhausting RAM, and what changes inside middleware when a view returns `StreamingHttpResponse`? - [Compiling URLResolver and path converters](https://djangointernals.dev/routing/urlconf.md): How does `path("stories//", ...)` turn into a compiled regular expression, and when is the URLconf tree actually imported and populated? - [Matching paths and reversing names](https://djangointernals.dev/routing/resolving-and-reversing.md): How does `URLResolver.resolve` walk nested includes in order, and how does `reverse` invert regex patterns back into concrete URL strings? - [Function views and decorator wrappers](https://djangointernals.dev/routing/views-and-decorators.md): What does a view decorator actually wrap, and why can stacking decorators in the wrong order or on async views break silently? - [View.as_view, MRO, and generic views](https://djangointernals.dev/routing/cbv-dispatch.md): Why does `View.as_view` allocate a brand-new view instance on every request, and how does Python's MRO assemble `ListView` and `DetailView`? - [Debug pages and response lifecycle](https://djangointernals.dev/routing/errors-and-debug.md): How does `ExceptionReporter` scrub sensitive variables for 500 error reports, and what closes a response after the view returns? ## 5. Security by default - [Security by default](https://djangointernals.dev/security.md): How CSRF tokens, cryptographic signing with fallback keys, CSP headers, and host checks work inside the middleware stack — and the exact edges where defaults stop protecting you. - [Allowed hosts, redirects, and proxy headers](https://djangointernals.dev/security/host-and-transport.md): Where does `HttpRequest.get_host` validate `ALLOWED_HOSTS`, and why do reverse proxies break HTTPS detection unless `SECURE_PROXY_SSL_HEADER` is configured carefully? - [CSRF tokens, masking, and origin checks](https://djangointernals.dev/security/csrf.md): Why does Django mask the CSRF secret differently on every HTML render, and what exact checks run on a POST over HTTP vs. HTTPS? - [Cryptographic signing and key rotation](https://djangointernals.dev/security/signing.md): How do `Signer` and `TimestampSigner` derive distinct keys via salts, and how does `SECRET_KEY_FALLBACKS` let you rotate keys without logging every user out? - [Content Security Policy and browser headers](https://djangointernals.dev/security/csp-and-headers.md): How does Django 6's built-in `ContentSecurityPolicyMiddleware` compile policy dictionaries and inject per-request nonces lazily? - [Framing rules and safe strings](https://djangointernals.dev/security/clickjacking-and-escaping.md): How does `XFrameOptionsMiddleware` guard responses against clickjacking, and how does `SafeString` propagate through Python string operations without losing its escape flag? - [Where Django's defaults stop protecting you](https://djangointernals.dev/security/where-defaults-stop.md): Which real vulnerabilities — authorisation, mass assignment, unsafe raw SQL, misordered middleware — sit entirely outside Django's built-in shields? ## 6. Models, metaclasses, and state - [Models, metaclasses, and state](https://djangointernals.dev/models.md): How `ModelBase` turns declarative field attributes into model options, descriptors, and database columns — and how every instance tracks its state against its row. - [What ModelBase.__new__ builds at import time](https://djangointernals.dev/models/metaclass.md): What actually happens to a model class dictionary when Python executes a `Model` subclass definition? - [Options, fields, and column metadata](https://djangointernals.dev/models/options-and-fields.md): What lives inside `Model._meta`, and how does a model field bridge Python types, database column types, and validation rules? - [Attribute access, deferred fields, and relations](https://djangointernals.dev/models/descriptors.md): Why does reading a deferred attribute or an unjoined foreign key on a model instance trigger a hidden SQL query? - [ModelState, instantiation, and from_db](https://djangointernals.dev/models/instance-state.md): How does a model instance know whether it came from the database or was constructed in memory, and why does `Model.from_db` skip default field computations? - [Inside Model.save: insert vs. update](https://djangointernals.dev/models/saving.md): How does `Model.save` decide between INSERT and UPDATE, why can saving an object with a preset primary key run two queries, and how does `update_fields` avoid lost updates? - [Collector, cascades, and fast deletes](https://djangointernals.dev/models/deleting.md): How does `Model.delete` walk every foreign key pointing at a row, when can it collapse deletions into a single SQL statement, and why can one signal receiver force Django to load thousands of rows into memory? - [Abstract bases, multi-table joins, and proxies](https://djangointernals.dev/models/inheritance.md): What database tables and SQL joins do abstract models, multi-table inheritance, and proxy models actually create? ## 7. QuerySets and laziness - [QuerySets and laziness](https://djangointernals.dev/querysets.md): A `QuerySet` is an unexecuted query description until something demands rows; chaining copies the description without touching the database, and the first evaluation fills an in-memory result cache. - [Chaining, cloning, and managers](https://djangointernals.dev/querysets/cloning.md): How do managers forward queryset methods, what does `QuerySet._clone` copy vs. share, and when does Django disable cloning in place? - [Evaluation and _result_cache](https://djangointernals.dev/querysets/caching.md): Which operations trigger `QuerySet._fetch_all`, which silently reuse `_result_cache`, and why is `if qs:` before slicing a classic production trap? - [Iterables, values, and streaming with iterator](https://djangointernals.dev/querysets/iterables.md): How do `ModelIterable`, `ValuesIterable`, and `ValuesListIterable` reshape identical cursor rows, and what does `QuerySet.iterator` trade away to save memory? - [Eager joins with select_related](https://djangointernals.dev/querysets/select-related.md): How does `QuerySet.select_related` turn foreign-key traversal into a single SQL JOIN, and how does `ModelIterable` split one wide result row into multiple model instances? - [Second-query batching with prefetch_related](https://djangointernals.dev/querysets/prefetch-related.md): How does `prefetch_related` eliminate N+1 queries on reverse foreign keys and many-to-many relations in Python, and why does chaining `QuerySet.filter` on a prefetched manager throw the cache away? - [Django 6.1 fetch modes](https://djangointernals.dev/querysets/fetch-modes.md): How do Django 6.1's `FETCH_ONE`, `FETCH_PEERS`, and `FETCH_RAISE` change lazy field and relation access without rewriting views? - [Updates, bulk_create, and cache invalidation](https://djangointernals.dev/querysets/bulk-writes.md): Why do `QuerySet.update` and `QuerySet.bulk_create` bypass `Model.save` and signals, and what happens to `_result_cache` and auto-generated primary keys? ## 8. From Python to SQL - [From Python to SQL](https://djangointernals.dev/sql.md): How `Q` objects, expressions, lookups, `Query` join promotion, and `SQLCompiler` compile a Python expression tree into parameterized SQL. - [Q objects and the WhereNode tree](https://djangointernals.dev/sql/q-and-where.md): How do `Q` expressions combine with `&`, `|`, `^`, and `~`, and how does `Query.build_filter` lower them into a `WhereNode` tree? - [Expressions, F, Value, and resolve_expression](https://djangointernals.dev/sql/expressions.md): What contract do `F`, `Value`, `Func`, `When`, and `CombinedExpression` share so Django can nest them arbitrarily inside filters, annotations, and updates? - [Lookups, transforms, and the lookup registry](https://djangointernals.dev/sql/lookups.md): How does Django parse `"published_at__year__gte"` into a chain of transforms ending in a lookup, and how does `RegisterLookupMixin` dispatch custom operators? - [Inside Query: alias maps and table joins](https://djangointernals.dev/sql/query-object.md): What data structures does `Query` hold — `alias_map`, `alias_refcount`, `table_map`, `select`, `where` — and how does it avoid duplicate table aliases? - [Inner vs. outer joins and multi-valued filter traps](https://djangointernals.dev/sql/join-promotion.md): Why do combining two lookups in one `QuerySet.filter` call and chaining two separate `QuerySet.filter` calls across a many-to-many relation generate completely different SQL and different row counts? - [SQLCompiler.as_sql and parameter binding](https://djangointernals.dev/sql/compiler.md): In what exact order does `SQLCompiler.as_sql` assemble SELECT, FROM, JOIN, WHERE, GROUP BY, HAVING, ORDER BY, and LIMIT clauses, and why are values never interpolated into the SQL string? - [Aggregates, annotations, subqueries, and windows](https://djangointernals.dev/sql/subqueries.md): How do `annotate`, `aggregate`, `Subquery`, `OuterRef`, and `Window` alter the compiled SQL — and why can two unrelated `Count` annotations silently multiply each other's totals? ## 9. Connections, transactions, and migrations - [Connections, transactions, and migrations](https://djangointernals.dev/database.md): Connection lifecycles, `atomic` savepoints, `on_commit` hooks, how migrations replay history into a `ProjectState` graph, and how `BaseDatabaseSchemaEditor` rewrites live tables. - [Connection handlers, CONN_MAX_AGE, and teardown](https://djangointernals.dev/database/connections.md): How does `ConnectionHandler` isolate one connection per thread or coroutine, when does Django actually open a socket to the database, and what runs at `request_finished`? - [How database backends diverge beneath one API](https://djangointernals.dev/database/backends.md): Where do SQLite, PostgreSQL, MySQL, and Oracle actually differ inside Django's backend architecture — features, operations, validation, and vendor quirks? - [Autocommit, atomic, and savepoints](https://djangointernals.dev/database/transactions.md): How does Django run in autocommit mode by default, how does `django.db.transaction.atomic` nest via SQL savepoints, and why does catching a `DatabaseError` inside `atomic` poison the outer block? - [transaction.on_commit and post-commit ordering](https://djangointernals.dev/database/on-commit.md): Why does enqueueing a background task or sending an email inside an `atomic` block cause race conditions, and how does `django.db.transaction.on_commit` hold callbacks until the outermost commit succeeds? - [How migrations build a historical ProjectState](https://djangointernals.dev/database/project-state.md): Why doesn't `migrate` inspect your live database schema, and how does Django reconstruct historical model classes from migration files alone? - [Inside MigrationAutodetector](https://djangointernals.dev/database/autodetector.md): How does makemigrations turn the difference between two `ProjectState` snapshots into ordered operations, detect renames, and simplify them with `MigrationOptimizer`? - [BaseDatabaseSchemaEditor and table rewrites](https://djangointernals.dev/database/schema-editor.md): How does `BaseDatabaseSchemaEditor` turn abstract migration operations into backend-specific DDL, and why does altering one column on SQLite recreate the entire table? ## 10. Templates and forms - [Templates and forms](https://djangointernals.dev/presentation.md): Django compiles template source once into a tree of node objects backed by a stacked `RenderContext` with automatic HTML escaping, while forms run a deterministic three-stage cleaning pipeline. - [Lexing, parsing, and the NodeList tree](https://djangointernals.dev/presentation/lexing-and-parsing.md): How do Django's template lexer and parser turn source text into a compiled tree of template nodes, and how do block tags consume tokens until their closing tag? - [Context, RenderContext, and inheritance](https://djangointernals.dev/presentation/context-and-rendering.md): How does `Context` stack dictionaries for nested scopes, how does `ExtendsNode` resolve overridden `{% block %}` trees, and why must custom tags store per-render state in `RenderContext`? - [Cached loaders and automatic HTML escaping](https://djangointernals.dev/presentation/loaders-and-escaping.md): How much time does the cached template loader save, and how does `VariableNode.render` decide whether to HTML-escape a value? - [Form metaclasses, bound data, and widgets](https://djangointernals.dev/presentation/form-binding.md): How does `DeclarativeFieldsMetaclass` collect declared fields, why does `BaseForm.__init__` deep-copy them per request, and how does `BoundField` join a field, its value, and its widget? - [The full_clean pipeline and ValidationError](https://djangointernals.dev/presentation/validation.md): In what exact order do `to_python`, `validate`, `run_validators`, `clean_`, and `BaseForm.clean` execute — and what happens to `cleaned_data` when one field fails? - [ModelForm, _post_clean, and save](https://djangointernals.dev/presentation/model-forms.md): How does `ModelFormMetaclass` derive form fields from a model's `_meta`, and why does `BaseModelForm._post_clean` mutate `BaseModelForm.instance` even when the form turns out invalid? - [Formsets and management form integrity](https://djangointernals.dev/presentation/formsets.md): How does a `BaseFormSet` coordinate dozens of forms from one flat `POST` dictionary, and why does a missing or tampered `ManagementForm` abort validation immediately? ## 11. Sessions, auth, and the admin - [Sessions, auth, and the admin](https://djangointernals.dev/auth.md): How session cookies map to backends, how `AuthenticationMiddleware` defers database work behind a `LazyObject`, and how the Admin exercises every internal layer of Django at once. - [Session stores, cookies, and dirty tracking](https://djangointernals.dev/auth/sessions.md): How does `SessionMiddleware` avoid hitting the session store on requests that never touch the session, and when does `SessionBase.modified` force a write? - [LazyObject, get_user, and session hash verification](https://djangointernals.dev/auth/lazy-user.md): Why does `AuthenticationMiddleware` attach a `SimpleLazyObject` instead of fetching the user immediately, and how does `get_session_auth_hash` invalidate old sessions after a password change? - [Authentication backends and hash upgrades](https://djangointernals.dev/auth/backends-and-passwords.md): How does `authenticate` walk `AUTHENTICATION_BACKENDS`, why does `django.contrib.auth.hashers.check_password` run a dummy hash for nonexistent usernames, and how does Django upgrade password hashes silently on login? - [Permission checks, groups, and ContentType caching](https://djangointernals.dev/auth/permissions.md): How does `PermissionsMixin.has_perm` cache every permission for the lifetime of a user object, and why does `ContentTypeManager` keep a process-wide lookup cache? - [AdminSite, autodiscover, and dynamic URLs](https://djangointernals.dev/auth/admin-registry.md): 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? - [Inside ChangeList: filters, search, and queries](https://djangointernals.dev/auth/changelist.md): How does `ChangeList` translate admin query-string parameters into filters, search clauses, ordering, and pagination — and why can one careless `list_display` callable turn an admin page into an N+1 storm? - [changeform_view, inlines, and audit logging](https://djangointernals.dev/auth/changeform.md): How does `ModelAdmin._changeform_view` coordinate a parent `ModelForm`, multiple `BaseInlineFormSet`s, `django.db.transaction.atomic`, and `LogEntry` inside one POST? ## 12. Caching, signals, tasks, and files - [Caching, signals, tasks, and files](https://djangointernals.dev/services.md): Cache middleware ordering traps, the hidden synchronous cost of `Signal.send`, Django 6's native `django.tasks` framework, file storage backends, and thread-local localisation. - [Cache backends, key versioning, and stampedes](https://djangointernals.dev/services/cache-backends.md): How does `CacheHandler` isolate connections, how does `make_key` add prefixes and version numbers, and why does `LocMemCache` fail across multiple worker processes? - [Page caching and the middleware ordering trap](https://djangointernals.dev/services/cache-middleware.md): Why does Django split whole-site caching into two separate middleware (`UpdateCacheMiddleware` first, `FetchFromCacheMiddleware` last), and what breaks when they are placed beside each other? - [Signal.send, weak references, and synchronous cost](https://djangointernals.dev/services/signals.md): Why are Django signals strictly synchronous function loops rather than background queues, and why do weak references silently drop local-function receivers? - [Django 6's django.tasks framework](https://djangointernals.dev/services/tasks.md): How does Django 6's built-in `django.tasks` separate task definition from execution backend, and what actually runs when you call `Task.enqueue` under `ImmediateBackend` vs. `DummyBackend`? - [Storage, FieldFile, and lazy file opening](https://djangointernals.dev/services/storage.md): Why does accessing a file field attribute on a model instance never open a file on disk until code reads bytes, and how does `StorageHandler` decouple models from local filesystems vs. object stores? - [Thread-local languages and aware datetimes](https://djangointernals.dev/services/i18n-and-timezones.md): How do `django.utils.translation.activate` and `django.utils.timezone.activate` store active state per thread or coroutine, and why does mixing naive and aware datetimes blow up at the database boundary? ## 13. Commands, checks, and testing - [Commands, checks, and testing](https://djangointernals.dev/tooling.md): How `manage.py` discovers commands, how system checks guard startup, why the autoreloader spawns a child process, and how `TestCase` uses transaction rollbacks instead of recreating tables. - [manage.py, discovery, and BaseCommand](https://djangointernals.dev/tooling/commands.md): What runs between typing `python manage.py ...` and entering `BaseCommand.handle`, and why do some commands skip `django.setup` or system checks? - [The system check framework and --deploy guards](https://djangointernals.dev/tooling/checks.md): How does `CheckRegistry` collect checks from models, fields, settings, and third-party apps, and which security mistakes are caught only when `--deploy` is passed? - [Why runserver runs two processes](https://djangointernals.dev/tooling/autoreload.md): Why does `manage.py runserver` spawn a parent supervisor and a child worker, why does `AppConfig.ready` run twice in development, and how does `StatReloader` decide when to restart? - [Creating, cloning, and tearing down test databases](https://djangointernals.dev/tooling/test-databases.md): How does `DiscoverRunner` spin up isolated test databases, serialize initial state, and clone databases across `--parallel` workers? - [Why TestCase is fast and when TransactionTestCase is required](https://djangointernals.dev/tooling/testcase-rollbacks.md): How does `TestCase` isolate every test method in milliseconds via a rolled-back outer transaction, and why do `django.db.transaction.on_commit` hooks and multi-thread DB tests behave differently there? - [How Client bypasses the socket](https://djangointernals.dev/tooling/test-client.md): How does Django's test `Client` execute the full middleware, routing, view, and template stack without starting a server — and what subtle differences remain? ## 14. Where Django leaks - [Where Django leaks](https://djangointernals.dev/leaks.md): The full measured latency and query ladder of a single endpoint, the failure modes that cross layer boundaries in production, and the sharp Django 6.x shifts that trip up older mental models. - [The measured latency and query ladder of one endpoint](https://djangointernals.dev/leaks/cost-ladder.md): Where do the milliseconds actually go inside a real Django view — from URL regex matching and middleware dispatch to SQL round-trips and template rendering? - [Production outages that cross layer boundaries](https://djangointernals.dev/leaks/cross-layer-failures.md): Why do the worst Django bugs happen at the seams between two subsystems that each look clean on their own? - [Django 6.x shifts that trip up older mental models](https://djangointernals.dev/leaks/modern-django.md): Which architectural changes in Django 5.x and 6.1.3 invalidate habits learned from older tutorials and model training data? - [Directing AI agents with a model of Django internals](https://djangointernals.dev/leaks/directing-agents.md): What six questions catch 90% of subtle bugs in agent-generated Django code before it reaches production?