This document provides a high-level overview of Django's architecture and core subsystems. It explains how the major components work together to provide a full-stack web framework. For detailed information about specific subsystems:
Django is a batteries-included web framework that provides an Object-Relational Mapper (ORM), automatic admin interface, form handling, testing utilities, and extensive database abstraction layers. The framework emphasizes reusability, rapid development, and the DRY (Don't Repeat Yourself) principle.
Django is organized into distinct layers, each with specific responsibilities. The following diagram shows the major subsystems and their dependencies:
Sources:
The ORM is Django's database abstraction layer, centered around the QuerySet class and Model base class. The ORM translates Python code into SQL queries.
| Component | File | Purpose |
|---|---|---|
QuerySet | django/db/models/query.py303-2700 | Public API for database queries |
Query | django/db/models/sql/query.py231-2200 | Internal query state representation |
SQLCompiler | django/db/models/sql/compiler.py40-2000 | Converts Query to database-specific SQL |
Model | django/db/models/base.py | Base class for all model definitions |
| Expression classes | django/db/models/expressions.py1-2000 | F(), Q(), Case(), etc. |
The ORM pipeline follows this flow:
Sources:
For detailed ORM documentation, see Core Django ORM.
Django's admin is a reusable app that provides a full-featured CRUD interface for models. It's built on top of the ORM and forms system.
| Component | File | Purpose |
|---|---|---|
AdminSite | django/contrib/admin/sites.py | Registry for model admins |
ModelAdmin | django/contrib/admin/options.py128-2500 | Configuration for model display |
ChangeList | django/contrib/admin/views/main.py1-600 | Handles list views with filtering |
The admin automatically generates views based on model definitions and ModelAdmin configuration:
Sources:
For detailed admin documentation, see Admin Interface.
The forms system handles HTML form rendering, validation, and data cleaning.
| Component | File | Purpose |
|---|---|---|
Form | django/forms/forms.py | Base class for forms |
ModelForm | django/forms/models.py | Auto-generates forms from models |
| Field classes | django/forms/fields.py | Form field types |
| Validators | django/core/validators.py | Reusable validation functions |
For detailed forms documentation, see Forms and Validation.
Django provides a comprehensive testing framework built on Python's unittest.
| Component | File | Purpose |
|---|---|---|
TestCase | django/test/testcases.py | Database-backed test cases with transactions |
Client | django/test/client.py | Simulates HTTP requests |
DiscoverRunner | django/test/runner.py | Test discovery and execution |
For detailed testing documentation, see Testing Framework.
Introduced in Django 6.0, the built-in Tasks framework allows running code outside the HTTP request-response cycle. This is useful for offloading long-running operations.
| Component | File | Purpose |
|---|---|---|
@task decorator | django/tasks/__init__.py | Defines a function as a background task |
Task dataclass | django/tasks/models.py | Represents a task to be executed |
TaskResult | django/tasks/models.py | Stores the result of a task |
BaseTaskBackend | django/tasks/backends/base.py | Abstract base for task backend implementations |
ImmediateBackend | django/tasks/backends/immediate.py | Executes tasks immediately (for dev/testing) |
DummyBackend | django/tasks/backends/dummy.py | Discards tasks (for dev/testing) |
Tasks are defined using the @task decorator and enqueued via a configured backend:
Sources:
enqueueing)A typical Django request flows through multiple layers:
Sources:
Django supports multiple database backends through a unified API. The DatabaseWrapper class provides backend-specific implementations.
| Database | Backend Module | Minimum Version |
|---|---|---|
| PostgreSQL | django/db/backends/postgresql/base.py1-50 | 15+ |
| MySQL/MariaDB | django/db/backends/mysql/base.py1-50 | 8.4+ / 10.11+ |
| SQLite | django/db/backends/sqlite3/base.py1-50 | 3.37+ |
| Oracle | django/db/backends/oracle/base.py1-50 | 19+ |
Sources:
Each backend defines a DatabaseFeatures class that describes database capabilities:
| Feature | PostgreSQL | MySQL | SQLite | Oracle |
|---|---|---|---|---|
allows_group_by_selected_pks | Yes | No | No | No |
supports_over_clause | Yes | Yes | Yes | Yes |
has_native_uuid_field | Yes | No | No | No |
supports_partial_indexes | Yes | No | Yes | Yes |
Sources:
Django uses migrations to manage database schema changes. The migration system detects model changes and generates migration files.
Sources:
For detailed migration documentation, see Schema Migrations and DDL Operations.
Django uses a settings module for configuration, with lazy evaluation and defaults.
Key settings include:
| Setting | Purpose | Example |
|---|---|---|
DATABASES | Database connections | {'default': {'ENGINE': 'django.db.backends.postgresql'}} |
INSTALLED_APPS | Enabled applications | ['django.contrib.admin', 'myapp'] |
MIDDLEWARE | Request/response processors | ['django.middleware.security.SecurityMiddleware'] |
TEMPLATES | Template engine configuration | [{'BACKEND': 'django.template.backends.django.DjangoTemplates'}] |
SECURE_CSP | Content Security Policy | {"default-src": [CSP.SELF]} |
TASKS | Background task backends | {"default": {"BACKEND": "django.tasks.backends.immediate.ImmediateBackend"}} |
Sources:
SECURE_CSP)TASKS)For detailed configuration documentation, see Configuration System.
Django provides a command-line utility for administrative tasks:
Common commands:
| Command | Module | Purpose |
|---|---|---|
runserver | django/core/management/commands/runserver.py | Development server |
migrate | django/core/management/commands/migrate.py | Apply migrations |
makemigrations | django/core/management/commands/makemigrations.py | Generate migrations |
test | django/core/management/commands/test.py | Run tests |
shell | django/core/management/commands/shell.py | Interactive Python shell |
Sources:
For detailed management command documentation, see Management Commands.
Django components are designed to be independent. Models don't know about views, views don't require specific form implementations, and the ORM can be used without the web framework.
Model field definitions automatically generate database schema, form fields, and admin widgets. Validators are reusable across forms and models.
URL routing requires explicit configuration. Database queries use explicit QuerySet methods rather than "magic" behavior.
The ORM abstracts database differences through DatabaseFeatures and DatabaseOperations classes. The same model code works across PostgreSQL, MySQL, SQLite, and Oracle.
Sources:
The following table summarizes how major subsystems depend on each other:
| Component | Direct Dependencies | Purpose of Dependency |
|---|---|---|
QuerySet | Query, Model, DatabaseWrapper | Builds and executes database queries |
ModelAdmin | QuerySet, Form, ModelForm | Displays and edits model data |
Form | Field, Validator | Validates and cleans user input |
Migration | SchemaEditor, Model._meta | Evolves database schema |
TestCase | DatabaseWrapper, transaction | Provides test isolation |
SQLCompiler | Query, DatabaseOperations | Generates backend-specific SQL |
Task | BaseTaskBackend, Settings | Defines and enqueues background operations |
Sources:
Django 6.x introduces several significant features and improvements:
As detailed above, Django 6.0 introduces a built-in Tasks framework for running code asynchronously outside the main request-response cycle. This allows for better scalability and responsiveness by offloading time-consuming operations. Tasks are defined using the @task decorator and managed via configurable backends. docs/releases/6.0.txt98-137
Django 6.0 provides built-in support for Content Security Policy (CSP), enhancing protection against content injection attacks like XSS. CSP headers can be configured via SECURE_CSP and SECURE_CSP_REPORT_ONLY settings, supporting nonces and allowing trusted content sources to be declared. docs/releases/6.0.txt40-76
The {% csp_nonce_attr %} template tag can be used to apply nonces to script and link elements. docs/ref/templates/builtins.txt109-119
Sources:
nonces)The Django Template Language (DTL) in Django 6.0 now supports template partials using the {% partialdef %} and {% partial %} tags. This feature allows encapsulating and reusing small, named fragments within a single template file, promoting modularity without requiring separate files for each component. Partials can also be referenced using template_name#partial_name syntax with Engine.get_template() and render(). docs/releases/6.0.txt78-94
Sources:
PartialTemplate)Django 6.1 introduces model fetch modes, allowing more control over how model instances are retrieved from the database. This can optimize performance by fetching only necessary data or by using different data structures.
Sources:
Django 6.0 updates its email handling to use Python's modern email.message.EmailMessage API, replacing the older Compat32 API. This provides a cleaner, Unicode-friendly interface for composing and sending emails. docs/releases/6.0.txt139-154
Sources:
AdminSite.password_change_form attribute allows customizing the password change form. messages.DEBUG and messages.INFO now have distinct icons and styling. docs/releases/6.0.txt159-172GEOSGeometry.hasm property to check for M dimension in geometries. docs/releases/6.0.txt181-184Sources:
Refresh this wiki