GitHub

Django Internals

How Django works, read from its source: what each part owns, when it runs, and why it is built the way it is.

Django main at 4fab678 (2026-09-26), on its way to 6.2

Django’s documentation says how to use Django, and says it well. This book is about the other thing: how the framework itself works. It follows a request from the server’s call to the response, a model from its class statement to the SQL it produces, a template from text to output, and at each step it says which object is responsible, when that object runs, and what it hands to the next.

It is written for people who need a working model of the system, whether to debug it, to extend it, or to direct an agent that is doing either, and for the agents themselves. Every class, function and setting named here exists in Django’s source at the commit the book describes, and every passage names the code it is about, so a reader can go and look.

Contents

  1. 1 What Django is

    Django is a web framework written in Python: the code between a web server and a web application, which turns each HTTP request the server hands it into a response, keeps the application’s data as models over a relational database, and draws its pages from templates. This chapter is the map of it: the objects that carry it, how its parts lean on one another, how it is extended, and where it stops.

    1. 1.1 The parts of Django, and what each leans on
    2. 1.2 How Django is extended
    3. 1.3 Django’s neighbours
    4. 1.4 The design philosophies, in the code
    5. 1.5 Where Django came from, and who makes it

Part I · The request cycle

  1. 2 A request, end to end

    One HTTP request followed from the server’s call to the last byte of the response, through the handler and its middleware, the URL resolver, the view, the ORM from queryset to SQL, the template engine, and the response.

    1. 2.1 Before the first request
    2. 2.2 From the server’s call to the view
    3. 2.3 The URL is resolved and the view is called
    4. 2.4 A queryset becomes SQL
    5. 2.5 The template is rendered
    6. 2.6 The response returns to the server
  2. 3 Settings, apps and startup

    Startup makes a Python process a configured Django. django.conf.settings loads the module that "DJANGO_SETTINGS_MODULE" names at the first read or write of a setting, and django.setup populates the app registry, django.apps.apps: an AppConfig for each entry of settings.INSTALLED_APPS, and every application’s models imported. Until that call the registry refuses most questions, with AppRegistryNotReady where settings can be read.

    1. 3.1 The settings object
    2. 3.2 Logging
    3. 3.3 Populating the app registry
    4. 3.4 The registry and its models
    5. 3.5 Who calls django.setup
    6. 3.6 Overriding settings
  3. 4 Handlers and middleware

    The handler, a WSGIHandler or an ASGIHandler, is ordinarily the object a web server calls for each request. It builds the middleware chain from settings.MIDDLEWARE when it is made, and sends each request it makes into that chain, at whose centre stands the view.

    1. 4.1 Building the middleware chain
    2. 4.2 The centre of the chain
    3. 4.3 How an exception becomes a response
    4. 4.4 Sync and async in one chain
    5. 4.5 The two entry points
    6. 4.6 The general-purpose middleware
  4. 5 Requests and responses

    HttpRequest is the object a view is given and HttpResponse the object it returns. The handler makes a WSGIRequest or an ASGIRequest from what the server passed, at almost no cost, and each of the request’s collections is parsed the first time something reads it: GET, COOKIES, headers, and, from the body, POST and FILES. A response, an HttpResponse or a StreamingHttpResponse, is a status, headers, cookies and a body, which the handler hands to the server.

    1. 5.1 Making the request: WSGIRequest and ASGIRequest
    2. 5.2 Headers, host and scheme
    3. 5.3 QueryDict
    4. 5.4 The body: body, POST and FILES
    5. 5.5 Multipart parsing: MultiPartParser
    6. 5.6 Upload handlers and uploaded files
    7. 5.7 The response object
    8. 5.8 Streaming and file responses
    9. 5.9 Cookies
    10. 5.10 The helpers in django/utils/http.py
  5. 6 URL routing

    The URL resolver answers two questions from one description of a site’s addresses: which view serves this path, and which path leads to this view. The URLconf that ROOT_URLCONF names is made, by its calls of path and include, into a tree of URLResolver objects and the patterns under them; URLResolver.resolve walks the tree to turn a path into a ResolverMatch, or raises Resolver404, and reverse turns a pattern’s name and arguments back into a path.

    1. 6.1 From a URLconf to a tree
    2. 6.2 When a URLconf is imported
    3. 6.3 Routes, regular expressions and converters
    4. 6.4 Resolving a path
    5. 6.5 Reversing a name
    6. 6.6 normalize, and the patterns that cannot be reversed
    7. 6.7 Namespaces
    8. 6.8 Language prefixes and translated routes
    9. 6.9 The URL checks, and listing the patterns
    10. 6.10 The script prefix, the current URLconf and the caches
  6. 7 Views

    A view is the callable the URL resolver found for a request’s path: the handler calls it with the request and the arguments the resolver found for it, and it returns a response or raises an exception. View.as_view makes a class into a view and decorators such as never_cache wrap one; the generic views are view classes of Django’s own, and the error views and debug pages are Django’s answers to an exception raised inside the middleware chain.

    1. 7.1 What the handler asks of a view
    2. 7.2 View.as_view and dispatch
    3. 7.3 View decorators
    4. 7.4 Decorating a class: method_decorator
    5. 7.5 A middleware as a decorator
    6. 7.6 Asynchronous views
    7. 7.7 The shortcuts
    8. 7.8 The generic views
    9. 7.9 DetailView and ListView
    10. 7.10 The form views
    11. 7.11 The date views: a date, an interval and its neighbours
    12. 7.12 The seven date views
    13. 7.13 The error views
    14. 7.14 The debug pages and ExceptionReporter
    15. 7.15 What an error report hides
    16. 7.16 The static file view
  7. 8 Security

    Django’s security machinery includes four middleware and two small libraries. CsrfViewMiddleware ordinarily refuses a request that may change something, such as a "POST", unless it comes from the site’s own pages and carries a CSRF token from them; SecurityMiddleware, XFrameOptionsMiddleware and ContentSecurityPolicyMiddleware add headers that tell the browser what to refuse; and django.utils.crypto and django.core.signing make, from SECRET_KEY, the keyed hashes with which Django signs what it hands out. System checks tagged "security" look over many settings.

    1. 8.1 The CSRF secret and its token
    2. 8.2 The CSRF check: CsrfViewMiddleware.process_view
    3. 8.3 The security headers: SecurityMiddleware and XFrameOptionsMiddleware
    4. 8.4 Content Security Policy and the nonce
    5. 8.5 Secret keys and django.utils.crypto
    6. 8.6 Signing: Signer, TimestampSigner, dumps and loads
    7. 8.7 The security checks

Part II · The ORM

  1. 9 Models and fields

    A model class is put together while its class statement runs. A metaclass, ModelBase, hands the new class to every field in the body; each field enters itself in the class’s options object and leaves a descriptor where it stood; and a relation can put an attribute on the class it points at as well.

    1. 9.1 ModelBase: a class statement becomes a model
    2. 9.2 The options: what a model keeps as _meta
    3. 9.3 A field: the base class
    4. 9.4 The field classes
    5. 9.5 Inheritance: abstract bases, parents with tables and proxies
    6. 9.6 Managers
    7. 9.7 Constraints and indexes
    8. 9.8 The model checks
  2. 10 An instance and its row

    An instance of a model stands for one row: it holds the row’s values in its __dict__ under the fields’ attnames, with a state that says where it came from; it can fetch what it lacks when it is read, writes itself back table by table when it is saved, and is collected, ordinarily with what depends on it, before it is deleted.

    1. 10.1 An instance and its state
    2. 10.2 Deferred fields and the fetch modes
    3. 10.3 Saving an instance
    4. 10.4 Validating an instance
    5. 10.5 Deleting: the Collector
    6. 10.6 File fields
    7. 10.7 A child in two rows
  3. 11 QuerySets

    A QuerySet is a query that has been described and not yet run, and afterwards the rows it brought back. A method that refines it ordinarily returns a clone; the first time it is iterated, or asked its length or its truth, it sends its statement and keeps what comes back in a result cache; and an iterable class decides what each row becomes: a model instance, a dictionary, a tuple or a single value.

    1. 11.1 Clones: how a queryset is built
    2. 11.2 filter, exclude and Q objects
    3. 11.3 Annotations, ordering and the other methods that change the query
    4. 11.4 Combining querysets: the operators and union
    5. 11.5 Evaluation and the result cache
    6. 11.6 From rows to instances: ModelIterable
    7. 11.7 values and values_list: rows as dictionaries and tuples
    8. 11.8 Deferred fields in a queryset: defer and only
    9. 11.9 get, first, count and the other methods that run a query at once
    10. 11.10 Creating, updating and deleting through a queryset
    11. 11.11 bulk_create and bulk_update
    12. 11.12 Raw querysets
    13. 11.13 The asynchronous methods of a queryset
  4. 12 Relations

    A relation is one fact written in one class and needed in two: a ForeignKey, a OneToOneField or a ManyToManyField on one model, and its rel, the same relation seen from the other. Each end ordinarily leaves an attribute on its class, and the related objects read through them may be kept in caches on the instance, filled by assignment, by a read, by a join in the same row or by a second statement.

    1. 12.1 Relations: a field, its rel and the class at the other end
    2. 12.2 Reading and setting related objects
    3. 12.3 Many-to-many relations
    4. 12.4 select_related: related objects from the same row
    5. 12.5 prefetch_related: related objects in a second query
    6. 12.6 The relation checks: RelatedField.check
  5. 13 Expressions, lookups and functions

    The objects of a query that write their own SQL: an expression is bound to a query by resolve_expression and written by as_sql; a lookup is a comparison, found by its name in a registry, prepared when the filter is built and written when the query is compiled; a function fills a template; and the where tree joins them, counting the children that match nothing or everything.

    1. 13.1 The lookup registry: RegisterLookupMixin
    2. 13.2 Expressions: resolve_expression and as_sql
    3. 13.3 Lookups: Lookup, BuiltinLookup and the standard comparisons
    4. 13.4 Transforms and database functions: Transform and Func
    5. 13.5 Lookups on relations and composite keys: RelatedIn and the tuple lookups
    6. 13.6 Aggregates: Aggregate and Count
    7. 13.7 Window expressions: Window and WindowFrame
    8. 13.8 What the where tree writes: WhereNode
  6. 14 Building a query

    A Query is the description of a statement that a queryset’s methods write and a compiler later reads: a filter’s names are walked through the models to joins in an alias map, the words left over become lookups in a where tree, and the conditions vote together on which joins are inner and which outer.

    1. 14.1 The query: what a Query holds, and how it is copied
    2. 14.2 From a name to a column: names_to_path, setup_joins and build_lookup
    3. 14.3 Tables and joins: the alias map and join promotion
    4. 14.4 The where clause: add_q and build_filter
    5. 14.5 Subqueries: Subquery, Exists, OuterRef and a query inside another
    6. 14.6 Merging two queries: Query.combine
  7. 15 The SQL compiler

    A SQLCompiler turns a query into one string of SQL with its parameters, sends it, and hands the rows back with their converters applied. It settles the clauses in the order they depend on one another and writes them in the order SQL wants, and where one "SELECT" cannot say what a queryset asks, it writes more than one, side by side or one inside another.

    1. 15.1 The compiler: as_sql, execute_sql and results_iter
    2. 15.2 The SELECT clause: get_select, the select mask and klass_info
    3. 15.3 ORDER BY and DISTINCT: get_order_by, find_ordering_name and get_distinct
    4. 15.4 GROUP BY and HAVING: set_group_by, get_group_by and split_having_qualify
    5. 15.5 Aggregating a query: Query.get_aggregation
    6. 15.6 The QUALIFY rewrite: a filter on a window
    7. 15.7 Compound statements: get_combinator_sql
    8. 15.8 INSERT, UPDATE and DELETE: the insert, update and delete compilers

Part III · The database

  1. 16 Connections and transactions

    Django holds a database as a connection object for each alias of DATABASES in each thread, opened when it is first needed and kept or closed at each request’s end; the statements of the compiler and of the schema editor pass through Django’s cursor, and under autocommit every write is its own transaction unless an atomic block makes it part of one.

    1. 16.1 Connections by alias: DATABASES and ConnectionHandler
    2. 16.2 Opening and closing a connection
    3. 16.3 Cursors: executing a statement, the query log and execute wrappers
    4. 16.4 Transactions: autocommit, atomic and savepoints
    5. 16.5 Work held until the commit: on_commit
    6. 16.6 Routing between databases: ConnectionRouter
  2. 17 Database backends

    A backend is the package that stands between the ORM and one kind of database. Its class of connection, built on BaseDatabaseWrapper, and the objects that connection carries say what the database can do, what SQL it writes, how a value crosses into it and back, and how its schema is read and changed; what differs between databases is decided in a few places, the same on every backend, and SQLite, PostgreSQL, MySQL and Oracle each depart from the plain case there.

    1. 17.1 The connection object: BaseDatabaseWrapper and what a backend provides
    2. 17.2 What a database can do: BaseDatabaseFeatures
    3. 17.3 The SQL a backend writes: BaseDatabaseOperations
    4. 17.4 Column types: from a field to a column
    5. 17.5 Values in and out: adapters, converters and time zones
    6. 17.6 Inserts: returned keys, conflicts and batch sizes
    7. 17.7 SQLite
    8. 17.8 PostgreSQL
    9. 17.9 MySQL and MariaDB
    10. 17.10 Oracle
  3. 18 Schemas and test databases

    Django changes a database’s structure from the models: a schema editor writes the DDL for one database and sends it, holding some statements, ordinarily until it is left; introspection reads the structure back where the models cannot answer; and for tests a whole database is made, in which migrate builds the models’ tables and the flush can empty them.

    1. 18.1 The schema editor: BaseDatabaseSchemaEditor
    2. 18.2 Altering a column, and SQLite’s table remake
    3. 18.3 Introspection: reading the schema back
    4. 18.4 Test databases: BaseDatabaseCreation
  4. 19 Migrations

    Migrations are how a change to a model becomes a change to a database. A migration file lists operations; makemigrations writes such files by comparing the models with what the existing files already describe, and migrate applies them to a database in the order their dependencies allow, recording each one there in the table "django_migrations".

    1. 19.1 A migration: its operations, its dependencies and how it is applied
    2. 19.2 Operations: the base class and its two halves
    3. 19.3 Project state: ProjectState and its model states
    4. 19.4 Historical models: StateApps and rendering
    5. 19.5 The model operations: CreateModel, DeleteModel, RenameModel and the option operations
    6. 19.6 The field operations, and those on indexes and constraints
    7. 19.7 RunPython, RunSQL and SeparateDatabaseAndState
    8. 19.8 What has been applied: MigrationRecorder and the table "django_migrations"
    9. 19.9 The migration graph: MigrationGraph
    10. 19.10 Finding migrations: MigrationLoader
    11. 19.11 Applying a plan: MigrationExecutor
    12. 19.12 The migrate command, showmigrations and sqlmigrate
    13. 19.13 Replacing migrations: replaces
  5. 20 Making migrations

    makemigrations compares two descriptions of the models, the one the migrations on disk add up to and the one the code gives now, and writes the difference as migrations: the autodetector finds the operations, orders them and cuts them into migrations, the optimizer folds them, and the writer turns each into the text of a file.

    1. 20.1 The autodetector: comparing two project states
    2. 20.2 The autodetector: fields, indexes and constraints
    3. 20.3 The questioner: MigrationQuestioner
    4. 20.4 From operations to migrations: dependencies, order and names
    5. 20.5 The optimizer: MigrationOptimizer and reduce
    6. 20.6 Serializing values: serializer_factory and deconstruct
    7. 20.7 Writing a migration file: MigrationWriter
    8. 20.8 The makemigrations command
    9. 20.9 Rewriting migrations: --update, squashmigrations and optimizemigration

Part IV · Templates, forms and services

  1. 21 Templates

    Django’s template system turns the name of a template and a dictionary of values into a string. It compiles a template’s text into a tree of nodes, by default once, and renders the tree against a fresh context each time it is asked, escaping for HTML as it goes. Around that language sits a thin layer of pluggable template engines, configured by TEMPLATES, through which a view asks for a template by name.

    1. 21.1 Template engines: TEMPLATES and the backends
    2. 21.2 Finding a template: Engine and the loaders
    3. 21.3 From text to nodes: the lexer and the parser
    4. 21.4 Variables and filters: FilterExpression and Variable
    5. 21.5 The context: Context, RequestContext and context processors
    6. 21.6 Rendering: nodes and the render context
    7. 21.7 Autoescaping and safe strings
    8. 21.8 Inheritance and inclusion: {% extends %}, {% block %} and {% include %}
    9. 21.9 Template partials: {% partialdef %} and {% partial %}
    10. 21.10 Libraries: Library, custom tags and {% load %}
    11. 21.11 The built-in tags
    12. 21.12 The built-in filters
    13. 21.13 The libraries to load: static, i18n, l10n, tz and cache
    14. 21.14 SimpleTemplateResponse and TemplateResponse
    15. 21.15 Template errors and debug information
  2. 22 Forms

    Django’s forms turn the strings a browser submits into checked Python values, and values back into HTML inputs. A form class declares its fields; each instance copies them and, bound to submitted data, cleans each value through the field’s widget, the field and its validators before the form’s own checks run. Formsets repeat one form over many rows, and a model form makes its fields from a model’s and writes what it cleaned back onto an instance.

    1. 22.1 Declaring a form: DeclarativeFieldsMetaclass and BaseForm
    2. 22.2 A form field: the base class
    3. 22.3 Validation: full_clean, cleaned_data and the errors
    4. 22.4 Validators: django/core/validators.py
    5. 22.5 The built-in form fields
    6. 22.6 Widgets: Widget and its subclasses
    7. 22.7 Choices: ChoiceField, ModelChoiceField and the choice widgets
    8. 22.8 BoundField: a field in a form
    9. 22.9 Rendering a form: renderers and templates
    10. 22.10 Form assets: Media
    11. 22.11 Formsets: BaseFormSet and the management form
    12. 22.12 Model forms: ModelForm and fields_for_model
    13. 22.13 Model formsets and inline formsets
  3. 23 Internationalization and time zones

    Django serves each request in a language and a time zone of its own, from code and templates written once: a message marked for translation is looked up as it is used, in the translations of the active language; numbers and dates are written in that language’s formats; and a datetime, stored as an instant, is shown in the current time zone. django.utils.translation, django.utils.formats and django.utils.timezone do the three, and LocaleMiddleware chooses each request’s language.

    1. 23.1 Translating a message
    2. 23.2 Message catalogues: DjangoTranslation
    3. 23.3 The active language
    4. 23.4 Lazy translations
    5. 23.5 Choosing a language: LocaleMiddleware
    6. 23.6 The language views: set_language and JavaScriptCatalog
    7. 23.7 Locale formats: get_format and the format modules
    8. 23.8 Writing numbers, dates and durations
    9. 23.9 Time zones
    10. 23.10 Making catalogues: makemessages and compilemessages
  4. 24 Caching, files, mail, signals and tasks

    The services that code all over Django, and a project’s own, calls into: the signal dispatcher, by which one part of the code hears of another’s events; the cache framework; file storage; email; background tasks; and the serializers and the paginator. Four of them share one shape: a setting of backends named by alias, a handler that makes a backend when it is asked for one, and a base class that every backend implements.

    1. 24.1 Signals: Signal, receivers and sending
    2. 24.2 The signals Django sends
    3. 24.3 The cache API: caches and BaseCache
    4. 24.4 The cache backends
    5. 24.5 The page cache: UpdateCacheMiddleware, FetchFromCacheMiddleware and cache_page
    6. 24.6 Cache headers and conditional requests: django/utils/cache.py
    7. 24.7 Files: File, ContentFile and their helpers
    8. 24.8 File storage: Storage, FileSystemStorage and storages
    9. 24.9 Email messages: EmailMessage and EmailMultiAlternatives
    10. 24.10 Sending email: mailers and the email backends
    11. 24.11 Background tasks: Task, TaskResult and the task backends
    12. 24.12 Serialization: serialize, deserialize and DeserializedObject
    13. 24.13 Fixtures: dumpdata and loaddata
    14. 24.14 Pagination: Paginator and Page
  5. 25 The utility layer

    The modules of django/utils/ that serve every part of Django and belong to none, with django.core.exceptions: the lazy values, lazy objects and cached properties by which code puts off work until it is needed, the importing of code named by a dotted path, the data structures and the helpers for text, values and paths that the request cycle and the ORM share, the exceptions they raise, and the tools with which Django deprecates its own API and names its versions.

    1. 25.1 Lazy values: lazy, Promise and keep_lazy
    2. 25.2 Lazy objects: LazyObject and SimpleLazyObject
    3. 25.3 cached_property, classproperty and classonlymethod
    4. 25.4 Importing by name: import_string and autodiscover_modules
    5. 25.5 Asking a callable what it accepts: django/utils/inspect.py
    6. 25.6 Data structures: MultiValueDict and its neighbours
    7. 25.7 Choices: normalize_choices and the choice iterators
    8. 25.8 Text and bytes: django/utils/encoding.py
    9. 25.9 Text helpers: Truncator and django/utils/text.py
    10. 25.10 Dates, durations and addresses: parse_datetime, parse_duration and clean_ipv6_address
    11. 25.11 Paths and archives: safe_join, safe_makedirs and extract
    12. 25.12 Django’s exceptions: django.core.exceptions
    13. 25.13 Deprecation: warnings named by year, warn_about_external_use and deprecate_posargs
    14. 25.14 Django’s version: VersionTuple and get_version

Part V · Applications and tools

  1. 26 Authentication, sessions and messages

    Three applications of django.contrib give a site the memory that HTTP lacks. django.contrib.sessions keeps a dictionary for each browser from one request to the next; django.contrib.auth keeps in that dictionary which user the browser belongs to, and checks passwords and permissions; django.contrib.messages keeps a note written while one request is answered until a later page shows it.

    1. 26.1 The session store: SessionBase
    2. 26.2 SessionMiddleware: the cookie and the save
    3. 26.3 The session backends
    4. 26.4 The user model: AbstractBaseUser, User and AUTH_USER_MODEL
    5. 26.5 Password hashing: make_password and the hashers
    6. 26.6 Password validation: validate_password and the validators
    7. 26.7 Authenticating: authenticate and the backends
    8. 26.8 The user of a request: login, logout and AuthenticationMiddleware
    9. 26.9 Permissions: Permission, groups and has_perm
    10. 26.10 Making the permissions: create_permissions
    11. 26.11 Requiring a login: login_required, permission_required and LoginRequiredMiddleware
    12. 26.12 The authentication forms: AuthenticationForm and the password forms
    13. 26.13 The login and password views: LoginView, LogoutView and PasswordChangeView
    14. 26.14 Password reset: PasswordResetTokenGenerator and the reset views
    15. 26.15 Creating a superuser: createsuperuser and changepassword
    16. 26.16 Messages: add_message, Message and MessageMiddleware
    17. 26.17 Message storage: CookieStorage, SessionStorage and FallbackStorage
  2. 27 The admin

    django.contrib.admin builds a working site for editing a project’s rows out of the models themselves. An AdminSite keeps a ModelAdmin for each model registered with it and turns them into a URLconf; each ModelAdmin serves its model’s list, add, change, delete and history pages, built from the model’s _meta and the model admin’s options, and asks the user’s permissions before each.

    1. 27.1 Registering models: AdminSite.register and ModelAdmin
    2. 27.2 The admin’s URLs: AdminSite.get_urls and AdminSite.admin_view
    3. 27.3 The site’s own pages: the index, the login and AdminSite.each_context
    4. 27.4 Permissions in the admin: has_change_permission and the others
    5. 27.5 The change form: changeform_view
    6. 27.6 The admin’s forms: get_form and formfield_for_dbfield
    7. 27.7 The admin’s widgets: related objects, raw ids and autocomplete
    8. 27.8 Inlines: InlineModelAdmin and its formsets
    9. 27.9 The change list: changelist_view and ChangeList
    10. 27.10 The change list’s columns: list_display and list_editable
    11. 27.11 Filters and search: list_filter, search_fields and date_hierarchy
    12. 27.12 Actions: response_action and delete_selected
    13. 27.13 Deleting: delete_view and get_deleted_objects
    14. 27.14 The log and the history: LogEntry and history_view
    15. 27.15 The admin’s templates and media
    16. 27.16 The admin’s checks: check_dependencies and ModelAdminChecks
    17. 27.17 The documentation generator: django.contrib.admindocs
  3. 28 Content types, static files and the other contrib apps

    The applications of django.contrib that are not authentication, sessions, messages or the admin: content types, which give the models rows of their own so that a row can point at any model; sites, which keep a row for each domain a project serves; static files, which find, collect, name and serve a project’s CSS, JavaScript and images; flat pages, redirects, sitemaps, feeds and humanize, small applications, most of them built on those; and the PostgreSQL and GIS extensions to the ORM.

    1. 28.1 Content types: ContentType and its cache
    2. 28.2 Making content types: create_contenttypes and RenameContentType
    3. 28.3 Generic foreign keys: GenericForeignKey
    4. 28.4 Generic relations: GenericRelation and generic inlines
    5. 28.5 Sites: Site, get_current_site and the shortcut view
    6. 28.6 Finding static files: the finders
    7. 28.7 Collecting static files: the collectstatic command
    8. 28.8 Static file storages: ManifestStaticFilesStorage and hashed names
    9. 28.9 Serving static files: StaticFilesHandler and the development server
    10. 28.10 Flat pages and redirects: the fallback middleware
    11. 28.11 Sitemaps: Sitemap and the sitemap views
    12. 28.12 Feeds: django.contrib.syndication and the feed generator
    13. 28.13 Humanize: naturaltime, intcomma and the other filters
    14. 28.14 The PostgreSQL application: PostgresConfig, operations and aggregates
    15. 28.15 PostgreSQL fields: ArrayField, the range fields and hstore
    16. 28.16 Full-text search: SearchVector, SearchQuery and SearchRank
    17. 28.17 PostgreSQL indexes and ExclusionConstraint
    18. 28.18 Geometries in Python: GEOS and GDAL
    19. 28.19 Spatial fields: the geometry fields and RasterField
    20. 28.20 Spatial backends: PostGIS, SpatiaLite, MySQL and Oracle
    21. 28.21 Spatial lookups, functions and distances
    22. 28.22 GeoDjango’s forms, admin, feeds and data tools
  4. 29 Management commands

    What happens between a command line such as python manage.py migrate and the code that does the work: ManagementUtility finds the command’s class, and BaseCommand parses the arguments, runs the system checks and calls the command’s handle. The development server is one such command, and its reloader runs it as two processes.

    1. 29.1 Finding the command
    2. 29.2 Running a command: BaseCommand
    3. 29.3 call_command: a command called from code
    4. 29.4 The system checks
    5. 29.5 The development server
    6. 29.6 The autoreloader
    7. 29.7 The commands Django ships
  5. 30 The test framework

    django.test runs a project’s tests, written as unittest test cases, against the project itself. The test command hands them to a runner, by default DiscoverRunner, which finds them, makes a test database for each database they use and runs them; the test case classes SimpleTestCase, TransactionTestCase and TestCase keep each test from seeing what another wrote to the database; and the Client sends requests through the project’s middleware and views with no server.

    1. 30.1 The runner: the test command and DiscoverRunner
    2. 30.2 Finding and ordering the tests: DiscoverRunner.build_suite
    3. 30.3 The test environment: setup_test_environment
    4. 30.4 Which databases a test uses: databases
    5. 30.5 One test, in order: SimpleTestCase
    6. 30.6 Emptying the tables after each test: TransactionTestCase
    7. 30.7 A transaction around each test: TestCase
    8. 30.8 Settings for one test: override_settings and TestContextDecorator
    9. 30.9 Building a request: RequestFactory
    10. 30.10 The test client: Client and ClientHandler
    11. 30.11 Sessions and logins in the test client: ClientMixin.login and force_login
    12. 30.12 Assertions on a response: assertContains, assertRedirects and assertTemplateUsed
    13. 30.13 Comparing HTML, XML and JSON: assertHTMLEqual and parse_html
    14. 30.14 Counting queries: assertNumQueries and CaptureQueriesContext
    15. 30.15 A server in a thread: LiveServerTestCase
    16. 30.16 Running in parallel: ParallelTestSuite
  6. 31 What changed

    How Django became what it is, from the framework released out of a newsroom in 2005 to this commit, and what a reader who learnt an earlier release must update: the changes from Django 5.0 on, where each now lives in the source, and the old uses the code keeps working until a coming release removes them.

    1. 31.1 The first decade: from a newsroom to 1.8
    2. 31.2 The second decade: from 1.9 to 5.0
    3. 31.3 What changed in settings, startup and the commands
    4. 31.4 What changed in handlers, requests, URLs and views
    5. 31.5 What changed in models and fields
    6. 31.6 What changed in querysets
    7. 31.7 What changed in expressions, lookups and the compiler
    8. 31.8 What changed in the database backends and migrations
    9. 31.9 What changed in templates
    10. 31.10 What changed in forms and validators
    11. 31.11 What changed in security: Content Security Policy and signing
    12. 31.12 What changed in time zones, translation and the utilities
    13. 31.13 What changed in mail and tasks
    14. 31.14 What changed in caching, files, signals, serialization and pagination
    15. 31.15 What changed in authentication, sessions and messages
    16. 31.16 What changed in the admin
    17. 31.17 What changed in the other contrib apps
    18. 31.18 What changed in GeoDjango
    19. 31.19 What changed in the test framework
    20. 31.20 Security fixes: SQL injection
    21. 31.21 Security fixes: disclosure, spoofing and privilege
    22. 31.22 Security fixes: limits against denial of service
    23. 31.23 The versions Django needs: Python, databases and libraries
    24. 31.24 What still warns: the deprecations and the releases that end them