Bookmarks
ReferenceBackendVerified

Django

Django is a Python web framework for websites and APIs with a database. The reference covers: models and the ORM, migrations, views, templates, the admin site, DRF and deployment.

checked 1 Nov · next check 8 Nov · 58 min read

Sections
14
Reading
58 min
Current version
6.1.3
Written from
docs.djangoproject.com/en/stable

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Django is and how it works

Django is a Python web framework for websites and APIs that work with a database. Out of the box it includes an ORM with migrations, URL patterns, templates, an admin site and authentication: the data is described once with model classes, and the database tables and the admin site are built from them.

Django is a good fit when database content needs to be displayed, edited and administered: catalogues, customer dashboards, internal systems, APIs for mobile clients. The parts of the framework are loosely coupled: you can use a different template engine or work without the ORM, although Django templates work best with its own models. If all you need is a JSON API, where the OpenAPI documentation and input validation are built from type annotations and no admin site is needed, consider FastAPI.

Every request follows the same path. The web server passes it to Django, and the middleware processes it in the order of the MIDDLEWARE list. The URLconf then picks a view, which assembles the response from model data and a template. On the way back, the response passes through the same middleware in reverse order.

A middleware can return a response itself, and the view is then not called.
  1. The middleware listed in MIDDLEWARE processes the request from top to bottom. Any of them can return a response straight away — the request then never reaches the view.
  2. Django loads the root URLconf from the ROOT_URLCONF setting and tries the URL patterns in urlpatterns in order until the first one matches the request path.
  3. Django calls the view of that URL pattern and passes it the HttpRequest and the values captured from the path, such as year=2026.
  4. The view reads data through the models, renders a template and returns an HttpResponse, or raises an exception such as Http404.
  5. If no URL pattern matched or an exception occurred, Django calls an error view — the 404, 500 and similar pages.
  6. The response passes through the middleware from bottom to top and goes to the web server.
pythoncatalog/urls.py
from django.urls import path from . import views urlpatterns = [    path("year/<int:year>/", views.books_by_year),]
pythoncatalog/views.py
from django.shortcuts import render from .models import Book  def books_by_year(request, year):    books = Book.objects.filter(published__year=year)    context = {"year": year, "books": books}    return render(request, "catalog/books_by_year.html", context)

Model, template, view (MTV)

In Django terms, the model describes the data, the template — how to display it, and the view — which data to show at that address. The role of the MVC “controller” is played by the framework itself: it directs the request to the right view via the URLconf. That is why Django is called an MTV framework: model, template, view.

How it differs from FastAPI

AspectDjangoFastAPI
Purposewebsites with HTML pages built on its own templates, and APIs backed by a databaseAPIs built on Python type annotations
Databaseits own ORM and migrationsno ORM of its own; the database is connected through a third-party library
Admin sitegenerated from the models; admin.site.register() is enoughnone
API schemadoes not build an OpenAPI schema; APIs are usually built with Django REST frameworkOpenAPI schema, Swagger UI and ReDoc generated automatically; data is validated by Pydantic models

Choose Django if the project has its own database, needs an admin site and pages for people, and the API is only one of its parts. Choose FastAPI for a standalone API service, where the API schema and type-based request validation matter more than models and an admin site.

What you need to know first

  • Python: functions, classes, modules, virtual environments — the Python reference.
  • HTTP: methods, response codes, headers — the HTTP and REST reference.
  • SQL basics: tables, keys, SELECT and JOIN — the SQL reference.

Section sources

the section is written from these pages

Cheat sheet

Everyday manage.py commands and ORM queries. The examples use the project mysite, the app catalog and the models Book and Author; substitute your own names. For how the commands work and where they go wrong, see the sections on migrations, queries, the admin site and deployment.

Project and apps

TaskCommand
Create a project in the current directorydjango-admin startproject mysite .
Create an apppython manage.py startapp catalog
Start the development serverpython manage.py runserver
Server on a different portpython manage.py runserver 8080
Expose the server to other machines on the networkpython manage.py runserver 0.0.0.0:8000
Check the project for errorspython manage.py check
Django versionpython -m django --version
Help for a commandpython manage.py help migrate

Migrations

TaskCommand
Create migrations from model changespython manage.py makemigrations
A migration with a descriptive namepython manage.py makemigrations catalog --name add_stock
An empty migration for datapython manage.py makemigrations catalog --empty
Apply all migrationspython manage.py migrate
Migrations and their [X] applied markspython manage.py showmigrations
The migration’s SQL without running itpython manage.py sqlmigrate catalog 0002
What migrate will do, without running itpython manage.py migrate --plan
Fail CI when a migration is missingpython manage.py makemigrations --check

Users, shell and data

TaskCommand
Create a superuserpython manage.py createsuperuser
Change a user’s passwordpython manage.py changepassword alice
Shell with the models already importedpython manage.py shell
Database console (psql, sqlite3)python manage.py dbshell
Dump an app’s data to JSONpython manage.py dumpdata catalog --indent 2
Load data from a fixturepython manage.py loaddata books.json

ORM queries: retrieval

TaskHow to write it
All objectsBook.objects.all()
Filter by a conditionBook.objects.filter(status="published")
Exclude by a conditionBook.objects.exclude(price__gte=100)
Exactly one object or an exceptionBook.objects.get(pk=1)
Case-insensitive substringBook.objects.filter(title__icontains="django")
A condition on a related modelBook.objects.filter(author__name="Ali")
An “OR” conditionBook.objects.filter(Q(price__lt=10) | Q(status="draft"))
Sort, newest firstBook.objects.order_by("-created")

ORM queries: relations, aggregates, updates

TaskHow to write it
Dictionaries instead of objectsBook.objects.values("title", "price")
Number of books per authorAuthor.objects.annotate(n=Count("books"))
Average price across all booksBook.objects.aggregate(Avg("price"))
Author in the same query via a JOINBook.objects.select_related("author")
Authors’ books in a separate queryAuthor.objects.prefetch_related("books")
Whether at least one record existsBook.objects.filter(status="draft").exists()
Update a field in a single UPDATEBook.objects.filter(pk=1).update(stock=F("stock") - 1)

Checks and deployment

TaskCommand
Settings checks for productionpython manage.py check --deploy
Collect static files into STATIC_ROOTpython manage.py collectstatic --noinput
Run the testspython manage.py test
Tests with deprecation warningspython -Wa manage.py test
Tests in parallel processespython manage.py test --parallel
Check that email can be sentpython manage.py sendtestemail admin@example.com

Dangerous commands

TaskCommand
Delete all data, keeping the tablespython manage.py flush
Roll the app back to migration 0001python manage.py migrate catalog 0001
Roll back all of the app’s migrationspython manage.py migrate catalog zero
Mark a migration as applied without running the SQLpython manage.py migrate catalog 0003 --fake
Clear STATIC_ROOT and collect againpython manage.py collectstatic --clear --noinput

Section sources

the section is written from these pages

Installation and first run

To install Django from PyPI into a virtual environment, run python -m pip install Django. django-admin startproject creates a project, and you check it with the development server: python manage.py runserver shows the welcome page at http://127.0.0.1:8000/.

Requirements

The 6.1 series runs on Python 3.12, 3.13 and 3.14, with Python 3.15 supported from release 6.1.3. Only the latest micro release of each Python series is officially supported, so install the latest Python of your series.

Development needs no separate database server: by default Django works with SQLite, which is included in Python. For production the documentation recommends PostgreSQL; MariaDB, MySQL and Oracle are also officially supported. If production will use PostgreSQL, develop on it from the start: SQLite differs from other databases in many ways.

Installing into a virtual environment

A virtual environment isolates a project’s packages from the system ones and needs no administrator rights. How environments are organised — see the Python reference, section “Installation and first run”.

bashLinux and macOS
mkdir mysite && cd mysitepython3 -m venv .venvsource .venv/bin/activatepython -m pip install Djangopython -m django --version

The last command prints the installed version; if Django is not installed, you get the error No module named django. On Windows, write py instead of python: py -m pip install Django.

A new project

A project is a set of settings and apps for one site. The dot at the end of the command puts manage.py in the current directory and the settings in the mysite package. Do not name the project django or test: these names clash with Django itself and with a built-in Python package.

bashin the project directory
django-admin startproject mysite .
textproject tree
.├── .venv/├── manage.py└── mysite/    ├── __init__.py    ├── asgi.py    ├── settings.py    ├── urls.py    └── wsgi.py
FileWhat it’s for
manage.pythe project’s command line: migrate, runserver, createsuperuser and more
mysite/settings.pysettings: apps, database, templates, static files
mysite/urls.pythe root URLconf — the “table of contents” of the site’s URLs
mysite/asgi.py, mysite/wsgi.pyentry points for ASGI and WSGI servers

First run

bashin the project directory
python manage.py migratepython manage.py runserver
textexample output
Performing system checks... System check identified no issues (0 silenced)....Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.

migrate creates tables for the built-in apps in INSTALLED_APPS: the admin site, authentication, content types and sessions. Open http://127.0.0.1:8000/ — a page with a rocket and the words “Congratulations!” will appear. The server restarts on its own when the code changes, but does not notice new files: after adding them, restart it manually.

The first app

An app is a Python package that does one thing: a catalogue, a blog, polls. A project consists of apps, and one app can be connected to several projects.

bashin the project directory
python manage.py startapp catalog
textapp tree
catalog/├── __init__.py├── admin.py├── apps.py├── migrations/│   └── __init__.py├── models.py├── tests.py└── views.py

Add the app to INSTALLED_APPS, otherwise Django will not see its models and migrations. The configuration class CatalogConfig lives in catalog/apps.py:

pythonmysite/settings.py
INSTALLED_APPS = [    "catalog.apps.CatalogConfig",    "django.contrib.admin",    "django.contrib.auth",    "django.contrib.contenttypes",    "django.contrib.sessions",    "django.contrib.messages",    "django.contrib.staticfiles",]

Connecting to PostgreSQL

PostgreSQL needs the psycopg driver (psycopg2 works as well). Create the database and the user in advance. For migrate to create tables, the user needs permissions to create and modify tables, and tests need the permission to create a test database.

bashin the project’s environment
python -m pip install psycopg
pythonmysite/settings.py
import os DATABASES = {    "default": {        "ENGINE": "django.db.backends.postgresql",        "NAME": "mysite",        "USER": "mysite",        "PASSWORD": os.environ["DB_PASSWORD"],        "HOST": "127.0.0.1",        "PORT": "5432",    }}

Section sources

the section is written from these pages

Models and fields

A model is a subclass of django.db.models.Model that describes a single table: each field of the class becomes a column. Django builds migrations, the query API, forms and the admin site from models, so the model is the only place where the data is described.

pythoncatalog/models.py
from django.db import modelsfrom django.urls import reverse  class Author(models.Model):    name = models.CharField(max_length=200)     def __str__(self):        return self.name  class Book(models.Model):    class Status(models.TextChoices):        DRAFT = "draft", "Draft"        PUBLISHED = "published", "Published"     title = models.CharField(max_length=200)    isbn = models.CharField(max_length=13, unique=True)    author = models.ForeignKey(        Author, on_delete=models.PROTECT, related_name="books"    )    price = models.DecimalField(max_digits=8, decimal_places=2)    stock = models.PositiveIntegerField(default=0)    status = models.CharField(        max_length=10, choices=Status, default=Status.DRAFT    )    published = models.DateField(null=True, blank=True)    created = models.DateTimeField(auto_now_add=True)     class Meta:        ordering = ["-created"]        constraints = [            models.CheckConstraint(                condition=models.Q(price__gte=0), name="price_gte_0"            ),        ]     def __str__(self):        return self.title     def get_absolute_url(self):        return reverse("catalog:book-detail", args=[self.pk])

The table will be named catalog_book: the app and model names in lower case. Django adds the id primary key itself, taking its type from the DEFAULT_AUTO_FIELD setting. For a ForeignKey an indexed author_id column appears in the table. To get the changes into the database, run makemigrations and migrate after editing the model.

Common field types

FieldWhat it is forRequired arguments
CharFieldshort text, VARCHARmax_length (PostgreSQL and SQLite can do without it)
TextFieldlong text—
IntegerField, PositiveIntegerFieldintegers—
DecimalFieldmoney and exact decimals, a value of type Decimalmax_digits and decimal_places; since Django 6.1, PostgreSQL, SQLite and Oracle can do without them
BooleanFieldyes or no—
DateField, DateTimeFielda date; a date and time—
EmailField, SlugField, URLFieldstrings with format validation—
JSONFieldJSON data—
ForeignKey, OneToOneField, ManyToManyFieldrelations between modelsthe related model; ForeignKey and OneToOneField also take on_delete

Field options

OptionWhat it doesDefault
null=Truestore an empty value as NULL in the databaseFalse
blank=Trueallow an empty value in forms and the admin siteFalse
defaulta default value; a function is called for each new object—
db_defaulta database-side default value—
unique=Truethe value is unique across the whole tableFalse
choicesallowed values; shown as a drop-down list in a form—
db_index=Truean index on the fieldFalse
auto_now_add, auto_nowthe time the object is created; the time of every save()False
verbose_name, help_texta label and a help text in forms and the admin site—

null concerns the database, blank concerns validation in forms. For the field to be optional in the form and in the database, both are needed: null=True, blank=True. The human-readable value of a field with choices is returned by the get_status_display() method.

Relations between models

ForeignKey is a many-to-one relation: a book has one author, an author has many books. related_name sets the name of the reverse relation: author.books.all(). The on_delete argument says what to do with the books when the author is deleted:

Value of on_deleteWhat happens when the author is deleted
CASCADEthe books are deleted too; Django emulates ON DELETE CASCADE and sends signals
PROTECTdeletion is forbidden: ProtectedError
RESTRICTdeletion is forbidden (RestrictedError) if the books are not deleted in the same operation by a cascade on another relation
SET_NULLNULL is written to author_id; null=True is required
SET_DEFAULT, SET()the default value or the result of a function
DO_NOTHINGnothing; if the database enforces the foreign key, an IntegrityError is raised
DB_CASCADE, DB_SET_NULL, DB_SET_DEFAULTthe same, done by the database itself via ON DELETE, without loading the objects into Python (since Django 6.1)

The DB_* options are faster: Django does not load the related objects before deleting. The trade-off is that with DB_CASCADE the pre_delete and post_delete signals are not sent. DB_SET_DEFAULT takes the value from db_default (not from default) and does not work on MySQL and MariaDB. Mixing DB_* with the Python options, except DO_NOTHING, in one model or in related models is not allowed.

ManyToManyField is a many-to-many relation; Django creates the intermediate table itself. The field is declared on only one of the two models. If the relation carries its own data — a date, a role, a quantity — describe an intermediate model and pass it in through:

pythoncatalog/models.py
class Reader(models.Model):    name = models.CharField(max_length=200)    books = models.ManyToManyField(Book, through="Loan")  class Loan(models.Model):    reader = models.ForeignKey(Reader, on_delete=models.CASCADE)    book = models.ForeignKey(Book, on_delete=models.CASCADE)    borrowed = models.DateField()

OneToOneField is a one-to-one relation: it is used when one object extends another, for example a profile complementing a user.

Meta: ordering, constraints, indexes

The nested Meta class describes everything that is not a field. The constraints in constraints are enforced by the database itself, so they also apply to data written bypassing Django.

Meta optionWhat it sets
orderingthe default ordering: ["-created"] — descending, ["title"] — ascending
constraintsUniqueConstraint, CheckConstraint — constraints in the database
indexesindexes, including ones over several fields: models.Index(fields=["title"])
verbose_name, verbose_name_pluralthe model name in the admin site; without it the class name is used, and an “s” is added for the plural
db_tablea custom table name instead of app_model

Model methods

Always define __str__(): it is the object’s string representation in the shell and the admin site. get_absolute_url() returns the object’s URL — the admin site and other parts of Django rely on it. Model methods work with a single row, while queries over the whole table go through the manager, objects by default: Book.objects.filter(...).

Section sources

the section is written from these pages

Queries and QuerySet

A QuerySet is a lazy description of a SELECT against a single model. filter(), exclude() and order_by() only build up the query; the SQL runs when the result is needed: on iteration, list(), len() or an if check. The main trap is N+1: a related object in a loop costs a separate query on every iteration.

Create, read, update, delete

pythonpython manage.py shell
from decimal import Decimal from catalog.models import Author, Book # create() creates and saves the object straight away: INSERTali = Author.objects.create(name="Ali Valiyev")book = Book(title="Django", isbn="9780000000001",            author=ali, price=Decimal("25.00"))book.save() # changes reach the database only on save(): UPDATEbook.price = Decimal("19.90")book.save() # a single object and a listbook = Book.objects.get(isbn="9780000000001")cheap = Book.objects.filter(price__lt=20) # DELETE: returns the number of deleted objects, broken down by modelbook.delete()

save() performs an INSERT for a new object and an UPDATE for an existing one; until you call it, the database is untouched. get() returns exactly one object: if there is none, you get Book.DoesNotExist; if there are several, Book.MultipleObjectsReturned. get_or_create() looks up the object or creates it and returns an (object, created) pair.

Filters and field lookups

A condition is written as field__lookup=value with a double underscore; without a lookup, exact is assumed. In the same way, __ follows relationships — Django adds the required JOINs itself. Each filter() returns a new QuerySet, so the calls can be chained.

LookupExampleSQL condition
exact (default)filter(status="draft")status = 'draft'
iexactfilter(title__iexact="django")case-insensitive equality
contains, icontainsfilter(title__icontains="web")LIKE '%web%', i — case-insensitive
gt, gte, lt, ltefilter(price__gte=10)price >= 10
infilter(pk__in=[1, 2, 3])id IN (1, 2, 3)
rangefilter(price__range=(10, 20))BETWEEN 10 AND 20
isnullfilter(published__isnull=True)published IS NULL
year, month, datefilter(created__year=2026)by part of the date
via a relationshipfilter(author__name__startswith="A")a JOIN with the authors table

The arguments to filter() are combined with a logical and. For or and not you need Q objects, while F refers to the value of a field in the database itself:

pythonpython manage.py shell
from django.db.models import F, Q # OR and NOT: Q objects are combined with |, & and ~Book.objects.filter(Q(price__lt=10) | ~Q(status="draft")) # one UPDATE without loading objects; save() is not calledBook.objects.filter(pk=1).update(stock=F("stock") - 1)

update() performs a single UPDATE: the save() method, the pre_save and post_save signals and the auto_now option do not fire. A bulk delete() also runs as one SQL command where possible, so your model’s delete() method may not be called.

Aggregates: aggregate and annotate

aggregate() computes values across the whole queryset and returns a dictionary; annotate() attaches a computed value to each object. The name of the result is given by a keyword argument.

pythonpython manage.py shell
from django.db.models import Avg, Count # a dictionary like {"avg_price": Decimal(...)}Book.objects.aggregate(avg_price=Avg("price")) authors = Author.objects.annotate(n_books=Count("books"))for author in authors:    print(author.name, author.n_books)

The N+1 queries problem

A loop over books that touches book.author runs 1 query to fetch the books and one more per book — 1 + N in total. That is how the default fetch mode FETCH_ONE works: the missing field is fetched for a single object. Related data should be fetched up front.

The more books, the more queries on the left; on the right the count does not grow.
MethodWhat it doesWhen
select_related("author")joins the related table with a JOIN in the same queryForeignKey and OneToOneField
prefetch_related("books")a separate query per relationship, joined together in Pythonmany-to-many and reverse relationships such as author.books
fetch_mode(models.FETCH_PEERS)on first access, fetches the field for all objects of the same QuerySet at oncewhen you do not know in advance which relationships will be needed (from Django 6.1)
fetch_mode(models.FETCH_RAISE)raises FieldFetchBlocked instead of fetchingwhere an extra query is an error (from Django 6.1)
pythonpython manage.py shell
from django.db import models # 1 query: books together with their authors via a JOINbooks = Book.objects.select_related("author") # 2 queries: authors and all their booksauthors = Author.objects.prefetch_related("books") # 2 queries without listing relationships, Django 6.1+books = Book.objects.fetch_mode(models.FETCH_PEERS)for book in books:    print(book.title, book.author.name)

How to see the SQL

With DEBUG = True, Django records every executed query in connection.queries — a list of dictionaries with the sql text and the time in seconds. Without DEBUG the list is not kept. The explain() method shows the query plan in the database; reading plans is covered in the PostgreSQL reference, section “Performance and EXPLAIN”.

pythonpython manage.py shell
from django.db import connection, reset_queries reset_queries()books = list(Book.objects.select_related("author")[:10])print(len(connection.queries))print(connection.queries[-1]["sql"])

Transactions

By default Django runs in autocommit mode: every query is committed to the database straight away. transaction.atomic() wraps a block of code in a transaction: on a clean exit the changes are committed, on an exception they are rolled back. atomic blocks can be nested inside one another.

pythoncatalog/services.py
from datetime import date from django.db import transactionfrom django.db.models import F from .models import Book, Loanfrom .tasks import notify_reader  @transaction.atomicdef lend(book, reader):    Book.objects.filter(pk=book.pk).update(stock=F("stock") - 1)    Loan.objects.create(book=book, reader=reader, borrowed=date.today())    # notify only after a successful COMMIT    transaction.on_commit(lambda: notify_reader(reader.pk))
TaskHow to do it
Several changes must go through togetherwrap them in atomic() — as a decorator or in a with block
The whole request as one transaction"ATOMIC_REQUESTS": True in the database settings; costly under load
An email, a task or a cache clear only after the committransaction.on_commit(); on rollback the call is discarded
Handle IntegrityError and carry oncatch the exception around a nested atomic(), not inside the block: otherwise the next query will raise TransactionManagementError

Section sources

the section is written from these pages

Migrations

A migration is a Python file in the app’s migrations/ directory that describes a schema change: adding a field, creating a model, adding an index. makemigrations writes such a file from changes to the models, and migrate applies it to the database. Store migrations in git together with the models.

The cycle is always the same. You change a model, and makemigrations compares the models with the migration history and writes a new file. You read this file, and migrate runs the SQL and records the migration in the django_migrations table. Django compares the models with the migration files, not with the database, so it does not notice changes made in the database by hand.

sqlmigrate only prints the SQL of the migration and changes nothing in the database.
bashin the project directory
python manage.py makemigrations catalogpython manage.py sqlmigrate catalog 0002python manage.py migratepython manage.py showmigrations catalog
textsample output
Migrations for 'catalog':  catalog/migrations/0002_book_stock.py:    + Add field stock to book

Read the output of makemigrations: the autodetector is not perfect and may misunderstand a complex change. sqlmigrate prints the SQL without running it — you can hand it to the database administrator. Commit the migration in the same commit as the model change so that colleagues and the server receive both together.

Inside the migration file

pythonmigrations/0002_book_stock.py
from django.db import migrations, models  class Migration(migrations.Migration):    dependencies = [("catalog", "0001_initial")]     operations = [        migrations.AddField(            model_name="book",            name="stock",            field=models.PositiveIntegerField(default=0),        ),    ]

dependencies sets the order: a migration that adds a ForeignKey to a model of another app depends on that app’s migration, and migrate runs them one after another. operations is a list of operations from which Django builds SQL for your database.

OperationWhat it does
CreateModel, DeleteModelcreates or deletes a table
AddField, RemoveField, AlterField, RenameFieldchanges columns
AddIndex, AddConstraintadds an index or a constraint
RunPythonruns Python code — for data migrations
RunSQLruns arbitrary SQL

Data migrations

Data is changed with a separate migration using RunPython. Create an empty migration and write the function in it. Get the model via apps.get_model(): this is the historical version of the model as of that migration, and a direct import will break the migration when the model changes. Historical models do not have your methods or your overridden save().

bashin the project directory
python manage.py makemigrations catalog --empty --name fill_stock
pythonmigrations/0003_fill_stock.py
from django.db import migrations  def fill_stock(apps, schema_editor):    Book = apps.get_model("catalog", "Book")    Book.objects.filter(status="published").update(stock=1)  class Migration(migrations.Migration):    dependencies = [("catalog", "0002_book_stock")]     operations = [        migrations.RunPython(            fill_stock, reverse_code=migrations.RunPython.noop        ),    ]

reverse_code runs on rollback; without it, rolling back such a migration raises an error. RunPython.noop means “do nothing on rollback”.

Rolling back migrations

bashin the project directory
# show which migrations will be rolled backpython manage.py migrate catalog 0002 --planpython manage.py migrate catalog 0002

migrate catalog 0002 brings the schema back to the state after migration 0002 and rolls back later migrations — together with migrations of other apps that depend on them. zero in place of the number rolls back all migrations of the app. A migration with an irreversible operation raises IrreversibleError when rolled back.

Do not edit a migration that has already been applied to other databases: there it is recorded as applied, and the edit will never reach them. Add the fix as a new migration.

Conflicts in a team

If two developers add migrations to the same app in parallel, two migrations with the same number appear. The number is for people; Django cares about names and dependencies: it will notice that the migrations are out of order and offer a way out. makemigrations --merge creates a merge migration if the changes do not contradict each other; otherwise fix the dependencies by hand.

bashin the project directory
python manage.py makemigrations --merge# in CI: non-zero exit code if migrations were forgottenpython manage.py makemigrations --checkpython manage.py migrate --check

Migrations in production

  • Run migrate as a separate deployment step with the same set of migrations that ran on staging: on identical data, migrations produce identical results.
  • PostgreSQL and SQLite run all operations of a migration in a single transaction. MySQL and Oracle run them without a transaction: if a migration fails halfway through, the changes have to be cleaned up by hand.
  • SQLite in production is not recommended for migrations: Django emulates a schema change by copying the table, which is slow and sometimes incorrect.
  • A unique required field is added to a table with data in three migrations: the field with null=True and no unique constraint, RunPython to fill in values, then AlterField with unique=True
  • A data migration on a large table can be run without a wrapping transaction: atomic = False on the Migration class and updates in batches inside transaction.atomic().

Section sources

the section is written from these pages

Views, URLs and forms

A view is a function or class that takes an HttpRequest and returns an HttpResponse or raises an exception such as Http404. Which view gets called is decided by the URLconf — the list of URL patterns, urlpatterns, where each pattern maps to a view.

App URLconf

pythoncatalog/urls.py
from django.urls import path from . import views app_name = "catalog"urlpatterns = [    path("", views.BookListView.as_view(), name="book-list"),    path("<int:pk>/", views.book_detail, name="book-detail"),    path("new/", views.book_create, name="book-create"),]
pythonmysite/urls.py
from django.contrib import adminfrom django.urls import include, path urlpatterns = [    path("books/", include("catalog.urls")),    path("admin/", admin.site.urls),]

include() strips the matched part of the URL and passes the rest to the included URLconf: a request for /books/7/ lands in book_detail with pk=7. URL patterns are checked in order, up to the first match. The leading slash is not written: every URL already has one. The pattern <int:pk>/ matches only URLs with a trailing slash, so /books/7 does not match it. The query string (?page=2) and the HTTP method play no part in the choice.

ConverterWhat it acceptsType in the view
str (by default)non-empty string without /str
intzero or a positive integerint
slugASCII letters, digits, - and _str
uuidUUID with hyphens, in lowercaseUUID
pathnon-empty string including /str

The pattern name (name) is there so URLs don’t have to be written by hand. In code the URL is built by reverse(), in a template by the {% url %} tag; with app_name the name gets a namespace:

pythonpython manage.py shell
from django.urls import reverse # returns "/books/7/"reverse("catalog:book-detail", args=[7])

If the built-in converters are not enough, re_path() accepts a regular expression — but then all values reach the view as strings.

Function-based view

pythoncatalog/views.py
from django.shortcuts import get_object_or_404, render from .models import Book  def book_detail(request, pk):    book = get_object_or_404(Book, pk=pk)    return render(request, "catalog/book_detail.html", {"book": book})
FunctionWhat it does
render(request, template, context)renders a template and returns an HttpResponse
get_object_or_404(Model, **kwargs)returns an object or raises Http404
get_list_or_404(Model, **kwargs)the same for a list: an empty list means Http404
redirect(to)redirects to an object (get_absolute_url()), a URL pattern name or a URL; 302
raise Http404("…")a 404 page; with DEBUG = False — the 404.html template from the root template directory, if one exists

redirect() responds with 302 by default, and with permanent=True — 301. To return a response with any status code, pass it to the constructor: HttpResponse(status=201).

Class-based views

The ready-made classes ListView and DetailView cover the standard “list” and “single object” pages. A model is enough for them: the default template is catalog/book_list.html (app and model), the list appears in the context as object_list and book_list, and context_object_name sets a custom name. In the URLconf the class is wired in through as_view().

pythoncatalog/views.py
from django.views.generic import ListView from .models import Book  class BookListView(ListView):    model = Book    context_object_name = "books"     def get_queryset(self):        return Book.objects.filter(status="published")

By default DetailView takes the primary key from the pk argument in the URL. A function is clearer when the logic is your own; a class is shorter when the page is standard — a list, an object, a form — and only the attributes change.

Model form

ModelForm builds a form from the model fields: field types and validation come from the model, and save() writes the object to the database. List the fields explicitly in fields: with "__all__" or exclude, a new model field ends up in the form by itself, and a user can fill it in.

pythoncatalog/forms.py
from django import forms from .models import Book  class BookForm(forms.ModelForm):    class Meta:        model = Book        fields = ["title", "isbn", "author", "price"]
pythoncatalog/views.py
from django.shortcuts import redirect, render from .forms import BookForm  def book_create(request):    if request.method == "POST":        form = BookForm(request.POST)        if form.is_valid():            book = form.save()            return redirect(book)    else:        form = BookForm()    return render(request, "catalog/book_form.html", {"form": form})

is_valid() validates both the form and the model: required fields, max_length, uniqueness. If the data is invalid, the same form with errors is returned to the template. save() creates the object, and with instance=book it updates an existing one; save(commit=False) returns the object without writing it to the database, so it can be completed before save().

Async views

A view can be declared with async def: Django detects this on its own and runs the view in an asynchronous context. The performance gain appears only under an ASGI server.

Section sources

the section is written from these pages

Templates

A template is a text file, usually HTML, with variables {{ }} and tags {% %}. The view passes it a context — a dictionary of data. By default the template escapes every variable, so user-entered text cannot turn into HTML and run a script.

Where Django looks for templates

The engines are configured in TEMPLATES. DIRS lists the directories to search for templates, in order; APP_DIRS: True adds the templates subdirectory of every app in INSTALLED_APPS. Put an app’s templates in catalog/templates/catalog/: the name catalog/book_list.html will not clash with an identically named template in another app.

pythonmysite/settings.py
TEMPLATES = [    {        "BACKEND": "django.template.backends.django.DjangoTemplates",        "DIRS": [BASE_DIR / "templates"],        "APP_DIRS": True,        "OPTIONS": {            "context_processors": [                "django.template.context_processors.request",                "django.contrib.auth.context_processors.auth",                "django.contrib.messages.context_processors.messages",            ],        },    },]

If a template is not found in any directory, Django raises TemplateDoesNotExist; if the template has a syntax error, TemplateSyntaxError.

Variables, filters and tags

The dot in {{ book.author.name }} tries, in turn, a dictionary key, then an attribute or method, then a list index; a method is called without parentheses or arguments. A missing variable is rendered as an empty string by default. A filter modifies the value after |, and filters can be chained.

htmlcatalog/templates/catalog/book_list.html
<ul>{% for b in books %}    <li>        <a href="{% url 'catalog:book-detail' b.pk %}">            {{ b.title }}        </a>        {{ b.published|date:"d.m.Y"|default:"not published" }}    </li>{% empty %}    <li>No books yet</li>{% endfor %}</ul><p>Total: {{ books|length }}</p>
FilterWhat it does
default:"…"substitutes a value when the variable is falsy: empty, 0, None
date:"d.m.Y"formats a date
lengththe length of a string or list
truncatechars:80truncates a string to 80 characters
pluralizethe plural ending
linebreaksturns line breaks into <p> and <br>
safedisables escaping — only for HTML you have checked
TagWhat it does
{% if %} … {% elif %} … {% else %}a condition; and, or, not, in and comparisons are available
{% for %} … {% empty %}a loop; empty — when the list is empty
{% url 'name' arg %}the address for a URL pattern name
{% include "…" %}inserts another template
{% csrf_token %}a hidden field with a CSRF token for a POST form
{% load static %}, {% static "…" %}the address of a static file

Template inheritance

The base template defines the page skeleton and the {% block %} tags; the child starts with {% extends %} and fills in only its own blocks. The parent block’s content is available as {{ block.super }}.

htmltemplates/base.html
{% load static %}<!DOCTYPE html><html lang="en"><head>    <title>{% block title %}Catalog{% endblock %}</title>    <link rel="stylesheet" href="{% static 'css/site.css' %}"></head><body>    {% block content %}{% endblock %}</body></html>
htmlcatalog/templates/catalog/book_detail.html
{% extends "base.html" %} {% block title %}{{ book.title }}{% endblock %} {% block content %}    <h1>{{ book.title }}</h1>    <p>{{ book.price }} UZS</p>{% endblock %}

Fragments: partialdef

Since Django 6.0, part of a template can be declared as a fragment with the {% partialdef %} tag and rendered with {% partial %} as many times as needed. A fragment can also be addressed from outside by name, template.html#fragment — in render() or {% include %}: this is how a piece of a page is served in response to an AJAX request.

htmlcatalog/templates/catalog/books.html
{% partialdef book-card %}    <article>{{ book.title }} — {{ book.author.name }}</article>{% endpartialdef %} {% for book in books %}    {% partial book-card %}{% endfor %}

Escaping and safe

By default, five characters are escaped in every variable: <, >, ', " and &. The string <script>alert('x')</script> from the database will be shown as text, not executed. The safe filter and the {% autoescape off %} block switch the protection off — apply them only to HTML that you have checked and sanitised yourself.

Rendering a form

{{ form }} renders all of the form’s fields with labels and errors. For a form that is submitted by POST to your own site, {% csrf_token %} is required inside <form>; do not add the token to forms that post to other sites — it would leak. The GET method suits only requests that change nothing, such as a search.

htmlcatalog/templates/catalog/book_form.html
<form method="post">    {% csrf_token %}    {{ form }}    <button type="submit">Save</button></form>

Section sources

the section is written from these pages

Admin site

The admin site is a ready-made staff interface that Django builds from your models: lists with search and filters, add and change forms, and a change history. It is enabled in a new project; all you need to do is register a model in admin.py.

Signing in and registering models

bashin the project directory
python manage.py createsuperuser

Open http://127.0.0.1:8000/admin/ and sign in. Users with is_staff = True can sign in to the admin site; a superuser gets all permissions. Models appear once registered — either with a call to admin.site.register(Book) or with a decorator:

pythoncatalog/admin.py
from django.contrib import admin from .models import Book, Loan  class LoanInline(admin.TabularInline):    model = Loan    extra = 1  @admin.register(Book)class BookAdmin(admin.ModelAdmin):    list_display = [        "title", "author", "price", "status", "is_available"    ]    list_filter = ["status", "published"]    search_fields = ["title", "isbn", "author__name"]    list_select_related = ["author"]    readonly_fields = ["created"]    inlines = [LoanInline]     @admin.display(boolean=True, description="In stock")    def is_available(self, obj):        return obj.stock > 0

The main ModelAdmin options

OptionWhat it configuresDefault
list_displaylist columns; fields, relations via __, methodsa single column — __str__()
list_filterfilters in the right-hand column of the listnone
search_fieldssearch; for text, icontains on each word of the queryno search
list_select_relatedwhich relations to load via select_related()False: only the relations used in list_display
list_per_pageobjects per page of the list100
fields, fieldsetsform fields and their groupsall editable fields
readonly_fieldsread-only fields, including methodsnone
inlinesrelated objects on the same page: TabularInline, StackedInlinenone
orderinglist orderingthe model’s Meta.ordering

Search splits the query into words and looks for objects where each word appears in at least one of the search_fields; for text fields it matches through icontains. An explicit lookup such as "stock__exact" searches a non-text field without converting it to text, and words that do not fit the field type are skipped. The filter type in list_filter depends on the field: for dates you get “Today”, “Last 7 days” and the like.

Actions on selected objects

An action is a function that a staff member applies to the selected rows of a list. It receives the ModelAdmin, the request and a QuerySet of the selected objects. permissions restricts the action to users with a given permission: add, change, delete or view.

pythoncatalog/admin.py
@admin.action(    permissions=["change"],    description="Publish selected books",)def publish(modeladmin, request, queryset):    queryset.update(status=Book.Status.PUBLISHED)

Add the action to BookAdmin: actions = [publish]. When the action runs, the admin site does not check per-object permissions — if that matters, check them inside the action itself with has_change_permission(request, obj). By default the action appears only in the list. Since Django 6.1, the location argument of the @admin.action decorator chooses where it appears: ActionLocation.CHANGE_FORM — the object page only, [ActionLocation.CHANGE_LIST, ActionLocation.CHANGE_FORM] — the list and the object page. ActionLocation is imported from django.contrib.admin.

Who should get admin access

The documentation recommends the admin site as an internal organisational tool only, not as the basis of a customer-facing interface. If the work follows a scenario rather than tables and fields — placing an order, approving a request — write your own views. The admin/ address in urls.py can be changed to anything else, and protect staff sign-in the same way as the rest of the site: HTTPS, strong passwords and permissions only for the models that need them.

Section sources

the section is written from these pages

REST API with Django REST framework

Django REST framework (DRF) is a library for JSON APIs on top of Django. A serializer turns model objects into JSON and validates incoming data. A viewset implements the “list”, “retrieve”, “create”, “update” and “delete” actions, and the router builds the URLs for it automatically.

Installation

bashin the project environment
python -m pip install djangorestframework
pythonmysite/settings.py
INSTALLED_APPS = [    # ...    "rest_framework",] REST_FRAMEWORK = {    "DEFAULT_PERMISSION_CLASSES": [        "rest_framework.permissions.IsAuthenticated",    ],    "DEFAULT_PAGINATION_CLASS": (        "rest_framework.pagination.PageNumberPagination"    ),    "PAGE_SIZE": 20,}

Serializer

pythoncatalog/serializers.py
from rest_framework import serializers from .models import Book  class BookSerializer(serializers.ModelSerializer):    class Meta:        model = Book        fields = ["id", "title", "isbn", "author", "price", "created"]

ModelSerializer creates fields and validators from the model — including uniqueness validators — and implements create() and update(). List the fields in fields explicitly: with "__all__", a new model field appears in the API response by itself. By default a foreign key is rendered as the primary key: "author": 3. AutoField fields and fields with editable=False — such as created with auto_now_add — are read-only on their own; make the others read-only with read_only_fields.

serializer.is_valid() validates the incoming data, and errors are stored in serializer.errors. With raise_exception=True, DRF itself returns a 400 response with a dictionary of errors keyed by field.

Viewset and router

pythoncatalog/api.py
from rest_framework import viewsets from .models import Bookfrom .serializers import BookSerializer  class BookViewSet(viewsets.ModelViewSet):    serializer_class = BookSerializer     def get_queryset(self):        books = Book.objects.select_related("author")        author = self.request.query_params.get("author")        if author:            books = books.filter(author_id=author)        return books
pythonmysite/urls.py
from django.urls import include, pathfrom rest_framework import routers from catalog.api import BookViewSet router = routers.DefaultRouter()router.register(r"books", BookViewSet, basename="book") urlpatterns = [    path("api/", include(router.urls)),    path("api-auth/", include("rest_framework.urls")),]

ModelViewSet implements the list, retrieve, create, update, partial_update and destroy actions; ReadOnlyModelViewSet implements only list and retrieve. If get_queryset() is overridden instead of the queryset attribute, the router needs a basename. Register the prefix without a trailing slash — the router adds it itself. api-auth/ adds login and logout for the browsable API: API pages open straight in the browser.

ClassWhat it provides
APIViewa class with get(), post() methods and DRF access rules
ViewSetthe list(), create() and other actions without ready-made implementations
ModelViewSetall six actions driven by queryset and serializer_class
ReadOnlyModelViewSetread-only: list and detail
@action(detail=True, methods=["post"])a custom action with a URL of the form books/7/publish/

Permissions

Permissions are checked before the view code runs. If a check fails, DRF responds with 403, and an unauthenticated user receives 401 or 403 depending on the authentication scheme.

ClassWho it allows
AllowAnyeveryone
IsAuthenticatedsigned-in users only
IsAdminUserusers with is_staff = True
IsAuthenticatedOrReadOnlyeveryone for reading (GET, HEAD, OPTIONS), signed-in users for writing
DjangoModelPermissionsby model permissions: POST — add, PUT and PATCH — change, DELETE — delete

A custom rule is a BasePermission subclass. In the example, only the object’s owner — the user in the model’s owner field — may change it. DRF’s generic views call the object-level check themselves, in get_object():

pythoncatalog/permissions.py
from rest_framework import permissions  class IsOwnerOrReadOnly(permissions.BasePermission):    def has_object_permission(self, request, view, obj):        if request.method in permissions.SAFE_METHODS:            return True        return obj.owner == request.user

Authentication: session and token

SessionAuthentication uses the Django session and suits JavaScript on the same site; for unsafe methods (POST, PUT, PATCH, DELETE) such a client must send the CSRF token. TokenAuthentication is a token in the Authorization header for mobile and other external clients. To enable it, add the rest_framework.authtoken app and the class to DEFAULT_AUTHENTICATION_CLASSES, run migrate and issue a token to the user.

pythonmysite/settings.py
INSTALLED_APPS = [    # ...    "rest_framework.authtoken",] REST_FRAMEWORK = {    # ...    "DEFAULT_AUTHENTICATION_CLASSES": [        "rest_framework.authentication.SessionAuthentication",        "rest_framework.authentication.TokenAuthentication",    ],}
bashin the project directory
python manage.py migratepython manage.py drf_create_token alice
bashclient
# token issued by drf_create_tokencurl http://127.0.0.1:8000/api/books/ \  -H "Authorization: Token $API_TOKEN"

The built-in implementation is minimal: one token per user, with no expiry. A client can obtain a token for a login and password through the obtain_auth_token view. The OAuth 2.0 and OpenID Connect protocols are covered in the OAuth and OIDC reference.

Pagination and response format

With PageNumberPagination the list comes in pages: the response contains the count, next, previous and results fields, and next holds the address of the next page. How to design URLs and choose response codes — see the HTTP and REST reference, the “Designing a REST API” and “Response codes” sections.

Section sources

the section is written from these pages

Production deployment

In production, Django runs behind a WSGI or ASGI application server, such as Gunicorn or Uvicorn. A web server sits in front of it: it handles HTTPS and serves static files itself. Before deploying, check your settings with python manage.py check --deploy.

A typical setup: nginx accepts the HTTPS requests, serves the /static/ files itself from the STATIC_ROOT directory, and passes the remaining requests to Gunicorn at 127.0.0.1:8000. Gunicorn keeps several worker processes running Django, and each of them talks to the database.

The collectstatic command fills STATIC_ROOT on every deployment.

WSGI or ASGI

FeatureWSGIASGI
What it isthe core Python standard for communication between a server and an applicationthe standard for asynchronous servers
Codesynchronous onlysynchronous and asynchronous: it unlocks the asynchronous capabilities of Python and Django
Entry pointmysite/wsgi.py, the application objectmysite/asgi.py, the application object
ServersGunicorn, uWSGI, Apache with mod_wsgi, GranianUvicorn, Daphne, Hypercorn, Granian

Choose WSGI and Gunicorn if your project’s code is synchronous, and ASGI if it has asynchronous views.

bashon the server, in the project directory
python -m pip install gunicorngunicorn mysite.wsgi \  --bind 127.0.0.1:8000 \  --workers 3

With no options, Gunicorn starts a single process with a single thread on 127.0.0.1:8000; the number of worker processes is set with --workers. Run it from the directory containing manage.py, so that the project is on the Python import path. For ASGI, Uvicorn will do. In production it is convenient to run it as a Gunicorn worker: Gunicorn keeps an eye on the processes and restarts the ones that crash.

bashon the server, in the project directory
python -m pip install uvicorn uvicorn-worker gunicornpython -m gunicorn mysite.asgi:application \  -k uvicorn_worker.UvicornWorker

Essential settings

pythonmysite/settings.py
import os DEBUG = FalseSECRET_KEY = os.environ["SECRET_KEY"]ALLOWED_HOSTS = ["example.com", "www.example.com"] STATIC_URL = "static/"STATIC_ROOT = "/var/www/example.com/static/"MEDIA_ROOT = "/var/www/example.com/media/" # once HTTPS is enabled on the web serverCSRF_COOKIE_SECURE = TrueSESSION_COOKIE_SECURE = True
SettingWhy it matters
DEBUG = Falsewhen True, the error page shows fragments of code, variables and project settings
SECRET_KEYa long random value, for production only, never in git; when you rotate the key, put the old one in SECRET_KEY_FALLBACKS
ALLOWED_HOSTSwith DEBUG = False, Django does not respond at all unless this has a matching value
DATABASESstore the database password the same way as SECRET_KEY; the database accepts connections only from the application server
CSRF_COOKIE_SECURE, SESSION_COOKIE_SECUREthe cookies will not travel over HTTP
STATIC_ROOTthe directory where collectstatic assembles the static files
LOGGING, ADMINSan error log; ADMINS receive emails about 500 errors

Email

Django sends error emails and notifications through the mail backend from the MAILERS setting. In development, emails are usually printed to the console or written to a file, while in production MAILERS points to a real SMTP server or an email service. Set the sender addresses in DEFAULT_FROM_EMAIL and SERVER_EMAIL: many mail servers reject mail from the default webmaster@localhost and root@localhost addresses.

Static and media files

In production, Django does not serve static files itself. collectstatic copies the static files of all installed apps into STATIC_ROOT, and the web server serves this directory at STATIC_URL. For cloud storage or a CDN, set your own backend in STORAGES["staticfiles"] — then collectstatic will upload the files there.

Users upload the media files in MEDIA_ROOT, so they cannot be trusted: the web server must not execute them as code — for example, an uploaded .php file. Include these files in your backups.

Deployment order

bashon the server, in the project directory
python -m pip install -r requirements.txtpython manage.py check --deploypython manage.py migrate --noinputpython manage.py collectstatic --noinputsudo systemctl restart gunicorn

Run check --deploy with the production settings — on the server or with --settings. Run the tests (python manage.py test) before deploying, in CI. The gunicorn service name in the last line is an example: that is what the systemd unit you created for the application server is called.

Nginx configuration is covered in the Nginx reference, section “Reverse proxy”; packaging into an image is covered in the Docker reference, section “Dockerfile and its instructions”.

Section sources

the section is written from these pages

Security

Django protects against common attacks by default: templates escape output (XSS), middleware checks the CSRF token, the ORM passes parameters to the database separately from the SQL, and the X-Frame-Options header thwarts clickjacking. safe, csrf_exempt and SQL assembled from strings by hand weaken this protection.

XSS: do not disable escaping

Escaping protects HTML only if you have not disabled it with the safe filter, the mark_safe function or an autoescape off block. HTML that is stored in the database and came from the user should be sanitised both on save and on output. Always put attribute values in quotes — without them the browser will read anything extra as a new attribute:

htmlthe wrong way
<div class={{ css_class }}>…</div>
htmlthe right way
<div class="{{ css_class }}">…</div>

CSRF

CsrfViewMiddleware is enabled in a new project. For every request except GET, HEAD, OPTIONS and TRACE it checks the cookie holding the secret and the form’s csrfmiddlewaretoken field; without them the response is 403. That is why GET must not change any data. The middleware also compares the Origin header, if the browser sent one, against the site’s address and CSRF_TRUSTED_ORIGINS, and for an HTTPS request without Origin it strictly checks Referer.

  • Put {% csrf_token %} in every POST form on your own site.
  • JavaScript sends the token in the X-CSRFToken header; the value is taken from the csrftoken cookie.
  • If forms are submitted from another domain or subdomain, add it to CSRF_TRUSTED_ORIGINS: ["https://shop.example.com"].
  • Use @csrf_exempt only if you know exactly why, for example for a webhook with its own signature.

SQL injection

ORM queries are protected: the SQL and the parameters are passed to the database driver separately. The risk appears in raw(), RawSQL, extra() and cursor.execute() if you paste a value into the SQL string yourself. Pass values as parameters:

pythonthe wrong way
Book.objects.raw(    f"SELECT * FROM catalog_book WHERE title = '{query}'")
pythonthe right way
Book.objects.raw(    "SELECT * FROM catalog_book WHERE title = %s", [query])

Clickjacking

XFrameOptionsMiddleware is enabled in a new project and sets the X-Frame-Options: DENY header: pages of the site cannot be embedded in another site’s <iframe> and placed under an invisible button. If the site embeds its own pages, set X_FRAME_OPTIONS = "SAMEORIGIN"; individual views are exempted with the @xframe_options_exempt decorator.

HTTPS and cookies

pythonmysite/settings.py
SECURE_SSL_REDIRECT = TrueSESSION_COOKIE_SECURE = TrueCSRF_COOKIE_SECURE = TrueSECURE_HSTS_SECONDS = 3600

SECURE_SSL_REDIRECT redirects HTTP to HTTPS; behind a reverse proxy it is easier to do this on the web server itself. The *_COOKIE_SECURE flags stop cookies from being sent over HTTP. HSTS tells the browser to reach the site over HTTPS only; it can be enabled on the web server instead of Django.

The Host header and ALLOWED_HOSTS

Django builds some addresses from the Host header, and a forged Host leads to cache and email link poisoning. That is why request.get_host() checks it against ALLOWED_HOSTS. Do not read Host directly from request.META — that bypasses the check.

Content Security Policy

Since Django 6.0 the CSP policy is set with built-in tools: middleware adds the Content-Security-Policy header according to the SECURE_CSP setting. Enable a new policy in SECURE_CSP_REPORT_ONLY mode first: the browser will report violations but block nothing. Do not exempt individual pages from the policy: a vulnerability on one page makes it possible to attack the rest.

pythonmysite/settings.py
from django.utils.csp import CSP MIDDLEWARE = [    # ...    "django.middleware.csp.ContentSecurityPolicyMiddleware",] SECURE_CSP = {    "default-src": [CSP.SELF],    "img-src": [CSP.SELF, "data:"],}

Passwords and secrets

Django stores not the password itself but a PBKDF2 hash with SHA256, a salt and an iteration count; another algorithm — Argon2, bcrypt, scrypt — is put first in PASSWORD_HASHERS. Complexity checks are set by AUTH_PASSWORD_VALIDATORS, and they are already enabled in a new project. There are four built-in validators: similarity to the user’s data, minimum length, a list of 20,000 common passwords and a ban on passwords made up of digits only. They run in the password change forms and in createsuperuser, but not in User.objects.create_user().

  • Keep SECRET_KEY and passwords outside the repository — in environment variables or in a file readable only by the app.
  • Django does not limit the rate of login attempts: protect against password brute-forcing with a web server module or a separate package.
  • Django has no built-in CORS headers — an API on another domain needs a package; the mechanism itself is described in the HTTP and REST reference, the “CORS” section.
  • Limit uploaded file sizes on the web server, and serve user files from a separate domain: a subdomain of the main site does not protect you.

The general list of web application risks is in the OWASP Top 10 reference; TLS settings are in the TLS and PKI reference, the “Security: recommended settings” section.

Section sources

the section is written from these pages

Common errors and diagnostics

Start with the exception message: with DEBUG = True Django shows a page with the traceback, the request and the settings, and in production the same goes to the application server’s log. python manage.py check finds configuration errors before you run anything.

Order of checks

  1. python manage.py check — models, settings, URLs; with --deploy — production settings as well.
  2. python manage.py showmigrations — whether all migrations have been applied.
  3. The Gunicorn or Uvicorn log; on a server — journalctl -u gunicorn.
  4. Locally with DEBUG = True — an error page with the traceback; do not enable this setting in production.

DisallowedHost and the 400 response

The cause: the request’s Host header matches none of the values in ALLOWED_HOSTS. With DEBUG = False and an empty ALLOWED_HOSTS, every request gets this response; with DEBUG = True, an empty list allows only localhost and its subdomains, 127.0.0.1 and [::1].

bashon the server
python manage.py shell -c \  "from django.conf import settings; print(settings.ALLOWED_HOSTS)"
pythonmysite/settings.py
ALLOWED_HOSTS = ["example.com", ".example.com"]

A value with a leading dot allows the domain and all its subdomains. "*" allows everything — then checking Host is up to you.

403 Forbidden when submitting a form

The cause: the request failed the CSRF check. The form has no {% csrf_token %}, JavaScript did not send the X-CSRFToken header, or the form was submitted from a domain that is not in CSRF_TRUSTED_ORIGINS.

htmlform template
<form method="post">    {% csrf_token %}    {{ form }}</form>
  • Make sure the template is rendered through render() or a generic view: that is how the token gets into the context.
  • For AJAX, send the X-CSRFToken header with the value of the csrftoken cookie.
  • Behind an HTTPS proxy, add the site’s address to CSRF_TRUSTED_ORIGINS: ["https://example.com"].
  • Look for the reason for the rejection in the django.security.csrf log.

TemplateDoesNotExist

The cause: the template is neither in the directories from DIRS nor in the templates directories of the apps. Or it is not looked for there: APP_DIRS is disabled or the app is not in INSTALLED_APPS. A common mistake is a template lying in catalog/templates/book_list.html while the view looks for catalog/book_list.html.

bashin the project directory
find . -path ./.venv -prune -o -name 'book_list.html' -print

Check TEMPLATES ("APP_DIRS": True in a new project) and put the file in catalog/templates/catalog/book_list.html. The error page with DEBUG = True lists every path where Django looked for the template.

Table not found after a model change

The cause: a migration was never created or never applied. The message comes from the database itself: in SQLite it says there is no such table, in PostgreSQL that the relation does not exist.

bashin the project directory
python manage.py showmigrations catalogpython manage.py makemigrations catalogpython manage.py migrate

Static files return 404 with DEBUG = False

The cause: runserver serves static files itself only while DEBUG = True; in production this is the web server’s job. Collect the files into STATIC_ROOT and configure the web server to serve that directory at the STATIC_URL address.

bashon the server
python manage.py findstatic css/site.csspython manage.py collectstatic --noinput

AppRegistryNotReady

The cause: models are used before Django has loaded the apps. This happens when an ORM query or gettext() runs while a models module is being imported, or when a standalone script has not called django.setup(). Write module-level translations with gettext_lazy().

pythoncount_books.py next to manage.py
import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")django.setup() # models are imported only after django.setup()from catalog.models import Book print(Book.objects.count())

ImproperlyConfigured

The cause: a value in settings.py is wrong or cannot be parsed — for example, a typo in a class path or a missing required key. The exception message names the setting; the check will surface any other configuration errors too.

bashin the project directory
python manage.py checkpython manage.py diffsettings

ImportError: cannot import name ...

The cause: a circular import — the models modules of two apps import each other. Reduce the dependencies between models modules, refer to a model by a string (ForeignKey("catalog.Book", ...)) and avoid doing extra work at import time.

RuntimeWarning: Accessing the database during app initialization is discouraged.

The cause: a database query runs while a module is being imported or in AppConfig.ready(). Such a query slows down every command and fails until the migrations are applied. A frequent case — a form’s choice list taken from the database:

pythoncatalog/forms.py
# the query runs at module import time — warningcountry = forms.ChoiceField(    choices=[c.name for c in Country.objects.all()])# the query runs when the form is renderedcountry = forms.ModelChoiceField(queryset=Country.objects.all())

Other exceptions

ExceptionCauseWhat to do
NoReverseMatchreverse() or {% url %} found no URL pattern by that name and argumentscheck the name, app_name and the number of arguments
Book.DoesNotExistget() found nothingget_object_or_404() in the view, or handle the exception
MultipleObjectsReturnedget() found more than one objectlook up by a unique field or use filter()
FieldErroran unknown field or lookup in filter() or order_by()check the field name and the __ relations
ProtectedErrordeletion is forbidden by on_delete=PROTECTdelete or rebind the related objects first
TransactionManagementErrora query after a database error inside the same atomic()catch the exception around the nested atomic()
SynchronousOnlyOperationsynchronous code, such as the ORM, is called from asynchronous codewrap the call in sync_to_async()
FieldFetchBlockeda field is fetched lazily while in FETCH_RAISE modeadd select_related() or prefetch_related()

Section sources

the section is written from these pages

Versions and what’s new

This reference describes Django 6.1. The latest release is 6.1.3, dated 3 November 2026. The 6.2 series will be the last one under the previous versioning and support policy. Starting with Django 2028, version numbers follow the years: a release every January, three years of support for each.

SeriesStatusLatest releaseSupported until
6.1mainstream support; described in this reference6.1.3mainstream — April 2027, extended — December 2027
6.0extended support: security and data loss6.0.10April 2027
5.2 LTSextended support: security and data loss5.2.19April 2028
4.2 LTSunsupported4.2.307 April 2026

Mainstream support covers security fixes, data loss bugs, crashes and regressions; extended support covers only security and data loss bugs. Patch releases stay compatible with their series, so it is always worth upgrading to the latest patch.

What is new in 6.1

  • “Queries and QuerySet”: the QuerySet.fetch_mode() fetch modes — FETCH_ONE (as before), FETCH_PEERS (reduces most N+1 cases to two queries) and FETCH_RAISE (forbids implicit fetching).
  • “Models and fields”: database-level on_delete — DB_CASCADE, DB_SET_NULL, DB_SET_DEFAULT; with DB_CASCADE, deletion signals are not sent.
  • “Deployment to production”: the MAILERS setting describes several mail backends, the way DATABASES and CACHES do; the choice is made with the using argument. check --deploy rejects a "default" entry containing development-only backends (mail.E001).
  • “The admin site”: @admin.action(location=...) chooses where the action is shown: in the list, on the object page, or both. list_select_related = False fetches only the foreign keys listed in list_display, and form fields sit under their labels.
  • “Security”: the PBKDF2 iteration count has grown from 1 200 000 to 1 500 000; signed cookies use a new salt scheme; old ones are accepted with SIGNED_COOKIE_LEGACY_SALT_FALLBACK = True.
  • “Installation and first run”: the minimum database versions are PostgreSQL 15, MySQL 8.4, MariaDB 10.11, SQLite 3.37.
  • Version numbering (DEP 20): the releases planned as 7.0 and 7.1 will be called Django 2028 and 2029; the RemovedInDjango70Warning class is renamed to RemovedInDjango2028Warning.

Deprecated and removed

WhatStatusWhat to use instead
EMAIL_BACKEND, EMAIL_HOST and other EMAIL_*deprecated in 6.1, removal — in Django 2028MAILERS
select_related() without argumentsdeprecated in 6.1, removal — in Django 2028a list of relations or FETCH_PEERS
list_select_related = Truedeprecated in 6.1, removal — in Django 2028a list of fields
values_list(flat=True) without a field namedeprecated in 6.1, removal — in Django 2028values_list("pk", flat=True)
{{ book..title }} in templatesdeprecated in 6.1, removal — in Django 2028a single dot
transaction.savepoint()deprecated in 6.1, removal — in Django 2028savepoint_create()
the all argument of staticfiles.finders.find()removed in 6.1find_all

Security releases

IdentifierWhat is affectedFixed in
CVE-2026-108147memory exhaustion in MultiPartParser when uploading a base64-encoded file6.1.3
CVE-2026-111211log injection through unescaped geometry values in forms6.1.3
CVE-2026-111362cross-site request forgery via the crs element in GeoJSON6.1.3
CVE-2026-113593private data leakage when the Vary header is empty or missing6.1.3
CVE-2026-113733password hash disclosure to view-only admin site users with a custom user model6.1.3
CVE-2026-114582cross-site request forgery via the SpatialReference string6.1.3
CVE-2026-77050denial of service in get_supported_language_variant()6.1.2, 6.0.9, 5.2.18
CVE-2026-84429denial of service when parsing HTTP headers (Accept, Content-Type)6.1.2, 6.0.9, 5.2.18
CVE-2026-87890cross-site request forgery via byte strings in GeoDjango spatial lookups6.1.2, 6.0.9, 5.2.18
CVE-2026-87975privilege escalation in model formsets with an editable primary key6.1.2, 6.0.9, 5.2.18
CVE-2026-15307arbitrary file write on the server and cross-site request forgery via spatial lookups6.1, 6.0.8, 5.2.17
CVE-2026-15337denial of service in check_for_language()6.1, 6.0.8, 5.2.17
CVE-2026-15830denial of service through nested geometry collections; refined in 6.1.26.1, 6.0.8, 5.2.17
CVE-2026-15920XSS via URLField values in the admin site6.1, 6.0.8, 5.2.17

The table lists vulnerabilities fixed in the 6.1, 6.1.2 and 6.1.3 releases; earlier ones are listed in Django’s archive of security issues.

Django REST framework

The DRF 3.18 series (since 7 August 2026) supports Django 5.2, 6.0 and 6.1 and no longer works with Django 4.2, 5.0 or 5.1. The latest release is 3.18.3, dated 6 October 2026; 3.18.2 fixed three vulnerabilities (GHSA-33wh-fxxf-88vv, GHSA-3547-9m27-7rxg, GHSA-xw6w-gcfp-cf8m) and added support for Python 3.15. A breaking change in 3.18: list validation errors (many=True) now come as a dictionary rather than a list; check the API clients that parse errors.

How to upgrade

  1. Read the release notes of every series between your current one and the target — above all the breaking changes and deprecated features.
  2. Upgrade one series at a time, each time to its latest patch; this is also how you move from LTS to LTS.
  3. Clear the deprecation warnings at your current version: python -Wa manage.py test.
  4. Upgrade Django and its dependencies, run the full test suite, then deploy.
  5. If you use Django’s cache, clear it after upgrading: cached objects may be unreadable by the new version.
bashin the project’s environment
python -m pip install -U Django

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Django” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61