Django Cheat Sheet: Every manage.py Command, the ORM, DRF and Deployment
Every built-in manage.py command, plus the ORM patterns, views, templates, settings, REST APIs, background jobs and deployment commands I reach for every day. Checked against Django 6.1. Every line comes with a short note on what it does.
DILJOT SINGH · TECHNICAL LEADDjango 6.1 · DRF 3.18 · Updated Dec 2026
Project & CLI
Setupmanage.py is your project's command line. It creates apps, runs the dev server, applies database changes and runs tests.
python -m venv .venv && source .venv/bin/activate # isolated Python env
pip install "django>=6.1,<6.2" # install Django 6.1.x
django-admin startproject config . # new project in this folder
python manage.py startapp blog # new app (a feature module)
python manage.py runserver 0.0.0.0:8000 # dev server with auto-reload
python manage.py makemigrations # turn model changes into migration files
python manage.py migrate # apply migrations to the database
python manage.py createsuperuser # admin login for /admin
python manage.py shell # REPL; models (5.2+) and settings, timezone etc. (6.0+) auto-imported
python manage.py dbshell # raw SQL client for your database
python manage.py collectstatic --noinput # gather static files for production
python manage.py check --deploy # flag insecure production settings
python manage.py test blog -v 2 --parallel # run tests, verbose, multi-processDjango 6.0 and 6.1 need Python 3.12 or newer (5.2 LTS still runs on 3.10 and 3.11). Add each new app to INSTALLED_APPS or Django won't see it. The full command list is in the next cards.
Official docsdjango-admin and manage.py (opens in a new tab)Tutorial part 1 (opens in a new tab)
Every built-in command
CLIdjango-admin <command> and python manage.py <command> run the same commands. manage.py also points Django at your project's settings, so use it inside a project.
Project
| Command | What it does |
|---|---|
startproject | Create a project skeleton (makes the folder if missing, 6.0+) |
startapp | Create an app skeleton |
check | Run system checks; --deploy adds production checks |
diffsettings | Show settings that differ from Django's defaults |
help / version | List commands or show one command's options / print the Django version |
Run & debug
| Command | What it does |
|---|---|
runserver | Development server with auto-reload. Never use it in production |
shell | Python REPL with Django loaded |
dbshell | Your database's own command-line client |
testserver | Dev server on a fresh test database loaded with fixtures |
sendtestemail | Send a test email to check your mail settings |
Database & migrations
| Command | What it does |
|---|---|
makemigrations | Write migration files from model changes |
migrate | Apply (or roll back) migrations |
showmigrations | List migrations and whether they are applied |
sqlmigrate | Print the SQL for one migration |
squashmigrations | Merge a range of migrations into one |
optimizemigration | Shrink the operations inside one migration |
inspectdb | Generate models from an existing database |
createcachetable | Create tables for the database cache backend |
sqlflush / sqlsequencereset | Print SQL to empty tables / reset ID sequences |
Data
| Command | What it does |
|---|---|
dumpdata | Export rows as JSON, XML or YAML fixtures |
loaddata | Import fixtures into the database |
flush | Delete all data, keep the tables |
Tests, i18n, static
| Command | What it does |
|---|---|
test | Run the test suite |
makemessages / compilemessages | Extract strings into .po files / compile them to .mo |
collectstatic | Copy all static files into STATIC_ROOT |
findstatic | Show which folder a static file is served from |
Contrib apps
| Command | What it does |
|---|---|
createsuperuser / changepassword | auth: create an admin user / reset a password |
clearsessions | sessions: delete expired sessions (run it on a schedule) |
remove_stale_contenttypes | contenttypes: remove types for deleted models |
ogrinspect | gis: generate a model from a geospatial file |
Official docsAvailable commands (opens in a new tab)Contrib app commands (opens in a new tab)
Flags every command accepts
CLIThese options work on any command, including your own custom ones.
python manage.py help # list all commands, grouped by app
python manage.py help migrate # options for one command
python manage.py migrate --settings=config.settings.prod # use another settings module
DJANGO_SETTINGS_MODULE=config.settings.prod python manage.py migrate # same, via env var
python manage.py migrate -v 2 # verbosity 0 (silent) to 3 (very chatty)
python manage.py check --traceback # full stack trace on errors
python manage.py migrate --no-color # plain output for log files
python manage.py migrate --skip-checks # skip system checks before running
python manage.py version # 6.1.xOfficial docsDefault options (opens in a new tab)
Run, shell & debug
CLICommands for day-to-day development: starting servers, poking at data and checking configuration.
django-admin startproject mysite --template=https://example.com/tpl.zip # start from a template
python manage.py startapp shop apps/shop # app inside an existing folder
python manage.py runserver 8001 # another port
python manage.py runserver 0.0.0.0:8000 # reachable from other devices (set ALLOWED_HOSTS)
python manage.py runserver --noreload # no auto-reload (debuggers, profilers)
python manage.py shell -i ipython # use IPython if installed
python manage.py shell -c "from blog.models import Post; print(Post.objects.count())" # one-liner
python manage.py shell --no-imports # skip the automatic imports
python manage.py dbshell -- -c "select count(*) from blog_post" # args after -- go to psql
python manage.py check --deploy --fail-level WARNING # CI: fail on any warning
python manage.py check --list-tags # see available check tags
python manage.py check --tag security # run one group of checks
python manage.py diffsettings --output unified # settings vs. defaults, as a diff
python manage.py sendtestemail [email protected] # test SMTP settings
python manage.py sendtestemail --admins # mail everyone in ADMINSOfficial docsrunserver (opens in a new tab)shell (opens in a new tab)check (opens in a new tab)
Data in & out
CLIMove data between databases, seed development data and reverse-engineer legacy tables.
python manage.py dumpdata blog.Post --indent 2 -o posts.json # one model, pretty JSON
python manage.py dumpdata blog -o blog.json.gz # whole app; .gz/.bz2/.xz compress
python manage.py dumpdata --natural-foreign --natural-primary \
-e contenttypes -e auth.Permission -o full.json # portable full dump
python manage.py dumpdata blog.Post --pks 1,2,3 # only these rows
python manage.py loaddata posts.json # import (searches fixtures/ dirs)
python manage.py loaddata full.json --ignorenonexistent # skip fields that no longer exist
python manage.py inspectdb > legacy/models.py # models from an existing DB
python manage.py inspectdb orders customers --include-views # only some tables / views
python manage.py flush --noinput # wipe all rows (dev only!)
python manage.py sqlsequencereset blog | python manage.py dbshell # fix IDs after imports
python manage.py createcachetable # needed for the DB cache backendFixtures skip save(), so custom save logic does not run. Signals still fire with raw=True.
Official docsdumpdata (opens in a new tab)loaddata (opens in a new tab)Providing initial data (opens in a new tab)
Test runner flags
CLIRun only the tests you need, so you get answers sooner.
python manage.py test # discover and run everything
python manage.py test blog.tests.PostTests.test_detail # one test method
python manage.py test -k slug # names matching a pattern
python manage.py test --keepdb # reuse the test DB between runs
python manage.py test --parallel auto # one process per CPU core
python manage.py test --failfast # stop at the first failure
python manage.py test --pdb # open the debugger on failure
python manage.py test --tag slow # only tests marked @tag("slow")
python manage.py test --exclude-tag slow # everything except those
python manage.py test --shuffle # random order, finds hidden coupling
python manage.py test --durations 10 # 10 slowest tests (5.0+)
python manage.py test --debug-sql # print SQL for failing tests
python manage.py test --buffer # hide output of passing tests
python manage.py testserver users.json # browse a DB loaded with a fixture
coverage run manage.py test && coverage report -m # coverage (pip install coverage)Official docstest (opens in a new tab)Running tests (opens in a new tab)
Users, i18n & static
CLIAdmin accounts, translations and static files from the command line.
python manage.py createsuperuser --username admin --email [email protected]
DJANGO_SUPERUSER_PASSWORD="$PW" python manage.py createsuperuser \
--noinput --username admin --email [email protected] # scripted (CI, Docker)
python manage.py changepassword alice # reset a user's password
python manage.py clearsessions # delete expired DB sessions (cron)
python manage.py remove_stale_contenttypes # tidy up after deleting models
python manage.py makemessages -l hi # create/update locale/hi/LC_MESSAGES/django.po
python manage.py makemessages -a # update every existing locale
python manage.py makemessages -d djangojs -l hi # strings from JavaScript files
python manage.py compilemessages # .po to .mo (needs GNU gettext)
python manage.py collectstatic --noinput --clear # wipe STATIC_ROOT, then copy fresh
python manage.py findstatic css/site.css -v 2 # where a file comes from, and search pathsOfficial docscreatesuperuser (opens in a new tab)makemessages (opens in a new tab)collectstatic (opens in a new tab)
Setup with uv
CLIuv is a fast Python package and project manager. It replaces venv + pip and keeps a lock file for repeatable installs.
uv init mysite && cd mysite # new project with pyproject.toml
uv add "django>=6.1,<6.2" "psycopg[binary]" # add deps, update uv.lock
uv add --dev pytest-django django-debug-toolbar # dev-only deps
uv run django-admin startproject config . # run inside the project env
uv run manage.py migrate # no need to activate the venv
uv run manage.py runserver
uv sync --locked # CI / Docker: install exactly uv.lockOfficial docsuv: working on projects (opens in a new tab)
Models
DataA model is a Python class that maps to one database table. Each attribute is a column; Django writes the SQL for you.
from django.conf import settings
from django.db import models
from django.urls import reverse
class Post(models.Model):
class Status(models.TextChoices): # fixed set of allowed values
DRAFT = "draft", "Draft" # (stored value, human label)
PUBLISHED = "pub", "Published"
title = models.CharField(max_length=200) # short text column
slug = models.SlugField(unique=True) # URL-safe id, no duplicates
body = models.TextField(blank=True) # long text, optional in forms
status = models.CharField(max_length=5, choices=Status, default=Status.DRAFT)
author = models.ForeignKey( # many posts -> one user
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE, # delete posts with the user
related_name="posts", # user.posts.all()
)
tags = models.ManyToManyField("Tag", blank=True) # many-to-many via join table
created = models.DateTimeField(auto_now_add=True) # set once on insert
updated = models.DateTimeField(auto_now=True) # set on every save
class Meta:
ordering = ["-created"] # default sort, newest first
indexes = [models.Index(fields=["status", "created"])] # speed up common filter
constraints = [ # enforced by the database
models.UniqueConstraint(fields=["author", "title"], name="uniq_author_title"),
]
def __str__(self): # label in admin and shell
return self.title
def get_absolute_url(self): # canonical URL for this object
return reverse("blog:detail", args=[self.slug])null=True lets the database column hold NULL. blank=True lets forms leave the field empty. For text fields, use only blank=True and store empty strings.
Official docsModels (opens in a new tab)Field options (opens in a new tab)
Field types
DataPick the field that matches the data. It decides the column type, the form widget and the validation.
| Field | What it does |
|---|---|
CharField(max_length=) | Short text with a length limit: names, titles |
TextField | Long text with no limit: posts, notes |
IntegerField | Whole numbers; PositiveIntegerField blocks negatives |
DecimalField(max_digits, decimal_places) | Exact decimals. Use for money, never FloatField |
BooleanField | True / False flags |
DateField / DateTimeField | Dates and timestamps; auto_now_add sets on create, auto_now on every save |
EmailField / URLField | Text that must be a valid email or URL |
JSONField | Structured JSON; query keys with data__key |
UUIDField(default=uuid.uuid4) | Random, unguessable IDs for public URLs |
FileField / ImageField | Uploads saved under MEDIA_ROOT/upload_to |
ForeignKey | Many-to-one link: many comments, one post |
OneToOneField | Exactly one on each side: user and profile |
ManyToManyField | Many on both sides: posts and tags. through= adds extra columns |
on_delete: what happens when the parent row is deleted
| Option | What it does |
|---|---|
CASCADE | Delete the children too |
PROTECT | Refuse the delete while children exist |
RESTRICT | Like PROTECT, but allows it inside a cascade |
SET_NULL | Set the link to NULL (field needs null=True) |
SET_DEFAULT | Set the link to the field's default |
DO_NOTHING | Leave it to the database; can break integrity |
DB_CASCADE / DB_SET_NULL / DB_SET_DEFAULT | 6.1: the database does it with SQL ON DELETE. Faster, but no pre_delete / post_delete signals |
Official docsModel field reference (opens in a new tab)on_delete (opens in a new tab)
QuerySets
ORMA QuerySet is a lazy database query you build in Python. It only runs when you loop over it, slice with a step, or call list(), len() or bool().
Post.objects.all() # every row
Post.objects.filter(status="pub", created__year=2026) # WHERE ... AND ...
Post.objects.exclude(author__is_active=False) # WHERE NOT ...
Post.objects.get(pk=1) # exactly one row, else raises
Post.objects.order_by("-created")[:10] # newest 10 (LIMIT 10)
Post.objects.first() # first row or None
Post.objects.exists() # cheap "any rows?" check
Post.objects.count() # SELECT COUNT(*)
Post.objects.values("id", "title") # dicts, only these columns
Post.objects.values_list("id", flat=True) # plain list of ids
Post.objects.only("title") # load just some columns
Post.objects.distinct() # drop duplicate rows
tag, created = Tag.objects.get_or_create(name="django") # fetch, or insert if missing
tag, created = Tag.objects.update_or_create( # upsert
name="django", defaults={"slug": "django"},
)
Post.objects.filter(status="draft").update(status="pub") # one UPDATE, no save()
Post.objects.bulk_create(posts, batch_size=500) # many INSERTs at once
Post.objects.filter(pk=1).delete() # DELETE matching rows
post = await Post.objects.aget(pk=1) # async version (a-prefix)
async for p in Post.objects.filter(status="pub"): # async iteration
...Official docsMaking queries (opens in a new tab)QuerySet API (opens in a new tab)
Field lookups
ORMLookups go after a double underscore in filter() to say how to compare. They also follow relations: author__profile__city="Toronto".
| Lookup | What it does |
|---|---|
__exact / __iexact | Equals (the default) / equals ignoring case |
__contains / __icontains | Text contains a substring |
__startswith / __endswith | Text begins / ends with (i- variants ignore case) |
__in=[1, 2, 3] | Value is in a list or another QuerySet |
__gt __gte __lt __lte | Greater / less than (or equal) |
__range=(a, b) | Between a and b, inclusive |
__isnull=True | Value is NULL (or not, with False) |
__date __year __month | Compare one part of a date or datetime |
__regex / __iregex | Matches a regular expression |
Official docsField lookups (opens in a new tab)
Q, F & aggregates
ORMQ builds OR and NOT conditions, F points at a column's value inside the database, and aggregates compute sums, counts and averages in SQL.
from decimal import Decimal
from django.db.models import Q, F, Count, Sum, Avg, Exists, OuterRef, Subquery
from django.db.models.functions import Lower
Post.objects.filter(Q(status="pub") | Q(author=user)) # OR condition
Post.objects.filter(~Q(title__icontains="draft")) # NOT condition
Product.objects.update(price=F("price") * Decimal("1.1")) # +10% in SQL, no race
Product.objects.filter(stock__lt=F("reorder_level")) # compare two columns
(Author.objects.annotate(n=Count("posts")) # add a count to each row
.filter(n__gt=5)) # ...then filter on it
Order.objects.aggregate(total=Sum("amount")) # one dict for the whole set
Order.objects.values("customer").annotate(spend=Sum("amount")) # GROUP BY customer
User.objects.order_by(Lower("username")) # case-insensitive sort
latest = Comment.objects.filter(post=OuterRef("pk")).order_by("-created")
Post.objects.annotate(
last_comment=Subquery(latest.values("body")[:1]), # value from a subquery
has_comments=Exists(latest), # True / False per row
)Official docsQ objects (opens in a new tab)F() expressions (opens in a new tab)Aggregation (opens in a new tab)
Query performance
ORMThe N+1 problem: one query for the list, then one more for each row's related object. Load the relations up front instead.
from django.db.models import Prefetch
Post.objects.select_related("author") # JOIN for FK / one-to-one
Post.objects.prefetch_related("tags") # 1 extra query for M2M / reverse FK
Post.objects.prefetch_related( # prefetch with a filter
Prefetch("comments", queryset=Comment.objects.filter(approved=True)),
)
from django.db import models
Post.objects.fetch_mode(models.FETCH_PEERS) # 6.1: lazy FK loads batch for the whole list
Post.objects.fetch_mode(models.FETCH_RAISE) # 6.1: raise FieldFetchBlocked on any lazy load
print(qs.query) # see the SQL Django will run
print(qs.explain()) # database's query plan
Post.objects.iterator(chunk_size=2000) # stream rows, low memory
from django.db import connection
len(connection.queries) # queries run so far (DEBUG only)Install django-debug-toolbar locally to see every query a page runs.
Official docsDatabase access optimization (opens in a new tab)select_related (opens in a new tab)prefetch_related (opens in a new tab)
Transactions
ORMA transaction makes a group of writes all-or-nothing. If anything inside fails, every change is rolled back.
from django.db import transaction
from django.db.models import F
with transaction.atomic(): # start a transaction
acct = Account.objects.select_for_update().get(pk=1) # lock the row
acct.balance = F("balance") - 100 # subtract in SQL
acct.save(update_fields=["balance"]) # write only that column
transaction.on_commit(lambda: notify(acct.pk)) # run after a successful commit
@transaction.atomic # whole function is one transaction
def transfer(src, dst, amount):
...ATOMIC_REQUESTS = True in a database setting wraps every request in a transaction.
Official docsDatabase transactions (opens in a new tab)
Migrations
DataMigrations are versioned files that change your database schema to match your models. Commit them to git with the code.
python manage.py makemigrations blog --name add_slug # create one with a clear name
python manage.py migrate blog 0003 # move forward or back to 0003
python manage.py migrate blog zero # undo all of blog's migrations
python manage.py showmigrations # list applied [X] and pending [ ]
python manage.py sqlmigrate blog 0003 # print the SQL a migration runs
python manage.py makemigrations --empty blog # blank file for custom code
python manage.py squashmigrations blog 0001 0010 # merge many into one
python manage.py makemigrations --check --dry-run # CI: fail if one is missingData migration: change rows, not schema
from django.db import migrations
from django.utils.text import slugify
def forwards(apps, schema_editor):
Post = apps.get_model("blog", "Post") # model as it was at this point in history
for p in Post.objects.filter(slug=""): # rows that need fixing
p.slug = slugify(p.title) # "Hello World" -> "hello-world"
p.save(update_fields=["slug"])
class Migration(migrations.Migration):
dependencies = [("blog", "0004_post_slug")] # run after this one
operations = [
migrations.RunPython(forwards, migrations.RunPython.noop), # noop = reversible
]Official docsMigrations (opens in a new tab)Data migrations (opens in a new tab)
URLs
WebURL patterns map a path to a view. Give each one a name so you can build links without hard-coding paths.
# config/urls.py: the root URL file
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls), # built-in admin site
path("blog/", include("blog.urls")), # hand /blog/... to the app
]
# blog/urls.py
from . import views
app_name = "blog" # namespace: "blog:detail"
urlpatterns = [
path("", views.PostList.as_view(), name="list"), # /blog/
path("<slug:slug>/", views.post_detail, name="detail"), # /blog/hello-world/
path("archive/<int:year>/", views.archive, name="archive"), # /blog/archive/2026/
]| Syntax | What it does |
|---|---|
<int:pk> | Digits, passed as an int |
<slug:slug> | Letters, numbers, hyphens, underscores |
<uuid:id> | A UUID, passed as a UUID object |
<str:name> / <path:p> | Any text without / and with / |
reverse("blog:detail", args=[s]) | Build a URL in Python |
{% url 'blog:detail' post.slug %} | Build a URL in a template |
Official docsURL dispatcher (opens in a new tab)Path converters (opens in a new tab)
Function views
WebA view takes a request and returns a response. Function views are the simplest kind: plain Python functions.
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.http import require_POST
def post_detail(request, slug):
post = get_object_or_404(Post, slug=slug, status="pub") # 404 if not found
return render(request, "blog/detail.html", {"post": post}) # HTML from a template
@login_required # send anonymous users to LOGIN_URL
@require_POST # reject GET with 405
def publish(request, pk):
post = get_object_or_404(Post, pk=pk, author=request.user) # only own posts
post.status = Post.Status.PUBLISHED
post.save(update_fields=["status"])
return redirect(post) # go to post.get_absolute_url()
def stats(request):
return JsonResponse({"posts": Post.objects.count()}) # JSON API response| Attribute | What it does |
|---|---|
request.method | "GET", "POST" and so on |
request.GET / .POST | Query string / form data |
request.FILES | Uploaded files |
request.user | Logged-in user, or AnonymousUser |
request.headers | HTTP headers, case-insensitive |
request.session | Per-visitor data that persists between requests |
Official docsWriting views (opens in a new tab)Request and response objects (opens in a new tab)Shortcuts (opens in a new tab)
Class-based views
WebGeneric class-based views handle common pages (lists, detail, create, edit) for you. You only override the parts that differ.
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.views.generic import CreateView, ListView
class PostList(ListView): # list page
model = Post
paginate_by = 20 # adds page_obj to the template
# template: blog/post_list.html (default name)
def get_queryset(self): # customise which rows show
return super().get_queryset().filter(status="pub").select_related("author")
class PostCreate(LoginRequiredMixin, CreateView): # form page, login required
model = Post
fields = ["title", "slug", "body"] # fields on the form
success_url = reverse_lazy("blog:list") # where to go after saving
def form_valid(self, form): # runs when the form passes validation
form.instance.author = self.request.user # set fields the user can't edit
return super().form_valid(form)| Class or method | What it does |
|---|---|
TemplateView | Render a template, no model |
DetailView | One object by pk or slug |
UpdateView / DeleteView | Edit or delete one object |
FormView | Any form not tied to a model |
RedirectView | Send the visitor somewhere else |
get_context_data() | Override to add extra template variables |
Official docsClass-based views (opens in a new tab)Generic views reference (opens in a new tab)
Templates
WebTemplates are HTML with {{ variables }} for output and {% tags %} for logic. Output is HTML-escaped automatically.
{% extends "base.html" %} {# inherit the site layout #}
{% load static humanize %} {# humanize needs django.contrib.humanize in INSTALLED_APPS #}
{% block content %} {# fill a slot defined in base.html #}
<h1>{{ post.title }}</h1>
<p>{{ post.created|date:"M j, Y" }}</p> {# Nov 28, 2026 #}
<p>{{ post.views|intcomma }} views</p> {# 12,400 #}
{{ post.body|truncatewords:50|linebreaks }} {# chain filters: cut text, then wrap in <p> #}
{% for tag in post.tags.all %} {# loop #}
<a href="{% url 'blog:tag' tag.slug %}">{{ tag }}</a>
{% empty %} {# when the list is empty #}
<em>No tags</em>
{% endfor %}
{% if user.is_authenticated %}Hi {{ user.first_name|default:"there" }}{% endif %}
<img src="{% static 'img/logo.svg' %}" alt=""> {# link to a static file #}
{% include "partials/share.html" with title=post.title %} {# reuse a snippet #}
<a href="{% querystring page=2 %}">Next</a> {# keep other ?params, set page #}
{% endblock %}Handy filters
| Filter | What it does |
|---|---|
default:"n/a" | Fallback when the value is empty |
length | Number of items or characters |
pluralize | Adds "s" when the count isn't 1 |
floatformat:2 | Round to 2 decimal places |
timesince | "3 days, 2 hours" since a date |
join:", " | Turn a list into one string |
safe | Skip escaping. Only for HTML you trust |
json_script:"id" | Pass data to JavaScript safely |
forloop.counter / .first / .last | Position inside a for loop |
Official docsTemplate language (opens in a new tab)Built-in tags and filters (opens in a new tab)
Forms
WebForms render inputs, validate what users submit and give you clean Python values. A ModelForm builds itself from a model.
from django import forms
class ContactForm(forms.Form): # form not tied to a model
email = forms.EmailField() # validates email format
message = forms.CharField(widget=forms.Textarea, max_length=2000)
def clean_email(self): # extra check for one field
email = self.cleaned_data["email"].lower()
if email.endswith("@example.com"):
raise forms.ValidationError("Use a real address.") # shown under the field
return email # value that ends up in cleaned_data
def clean(self): # checks across several fields
return super().clean()
class PostForm(forms.ModelForm): # form generated from a model
class Meta:
model = Post
fields = ["title", "slug", "body", "tags"] # which model fields to include
widgets = {"body": forms.Textarea(attrs={"rows": 8})} # customise inputs
def contact(request):
form = ContactForm(request.POST or None) # bound on POST, empty on GET
if request.method == "POST" and form.is_valid(): # runs all validation
send_message(**form.cleaned_data) # safe, typed values
return redirect("thanks") # redirect after POST
return render(request, "contact.html", {"form": form}) # show form + errors<form method="post">
{% csrf_token %} {# required on every POST form #}
{{ form.email.as_field_group }} {# label, input, help text, errors #}
{{ form.message.as_field_group }}
<button>Send</button>
</form>Official docsWorking with forms (opens in a new tab)ModelForm (opens in a new tab)
Admin
WebThe admin is a ready-made back office for your models. Register a model and configure how its list and edit pages look.
from django.contrib import admin
class CommentInline(admin.TabularInline): # edit comments inside the post page
model = Comment
extra = 0 # no blank rows by default
@admin.register(Post) # add Post to the admin
class PostAdmin(admin.ModelAdmin):
list_display = ["title", "author", "status", "created"] # columns in the list
list_filter = ["status", "created"] # sidebar filters
search_fields = ["title", "author__username"] # search box
prepopulated_fields = {"slug": ["title"]} # fill slug as you type the title
list_select_related = ["author"] # avoid N+1 (6.1 does this for FKs in list_display)
raw_id_fields = ["author"] # ID input instead of a huge dropdown
date_hierarchy = "created" # drill down by year / month / day
inlines = [CommentInline] # related rows on the same page
actions = ["make_published"] # bulk action in the dropdown
show_facets = admin.ShowFacets.ALWAYS # show counts next to filters
@admin.action(description="Publish selected posts")
def make_published(self, request, queryset): # queryset = the ticked rows
queryset.update(status=Post.Status.PUBLISHED)Official docsThe admin site (opens in a new tab)
Auth & permissions
SecurityDjango ships users, groups, permissions, login and password reset. You mostly configure them rather than build them.
from django.contrib.auth import get_user_model
User = get_user_model() # works with custom user models
user = User.objects.create_user("dj", email="[email protected]", password=pw) # hashes the password
user.check_password(pw) # True if it matches
user.has_perm("blog.change_post") # app_label.action_modelname
user.groups.add(editors) # give the group's permissions
# settings.py
AUTH_USER_MODEL = "accounts.User" # custom user; set before first migrate
LOGIN_URL = "login" # where @login_required sends people
LOGIN_REDIRECT_URL = "/" # where to go after logging in
# urls.py
path("accounts/", include("django.contrib.auth.urls")), # login, logout, password reset
# settings.py (5.1+): require login on every page
MIDDLEWARE += ["django.contrib.auth.middleware.LoginRequiredMiddleware"]
from django.contrib.auth.decorators import login_not_required # mark public viewsStart every project with a custom user model, even an empty subclass of AbstractUser. Switching later is painful.
Official docsUsing the auth system (opens in a new tab)Custom user model (opens in a new tab)
Settings for production
OpsThe settings that matter when you deploy: secrets from the environment, allowed hosts, a real database, static files and HTTPS.
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent # project root folder
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"] # signs cookies; never commit it
DEBUG = os.environ.get("DJANGO_DEBUG") == "1" # must be False in production
ALLOWED_HOSTS = ["diljotsingh.com", "www.diljotsingh.com"] # domains you serve
CSRF_TRUSTED_ORIGINS = ["https://diljotsingh.com"] # origins allowed to POST
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql", # Postgres driver
"NAME": os.environ["DB_NAME"],
"CONN_MAX_AGE": 60, # reuse connections for 60 s
"CONN_HEALTH_CHECKS": True, # drop dead connections
# or a psycopg pool (5.1+): "OPTIONS": {"pool": True} with CONN_MAX_AGE = 0
}
}
STATIC_URL = "static/" # URL prefix for CSS / JS
STATIC_ROOT = BASE_DIR / "staticfiles" # where collectstatic copies them
MEDIA_URL = "media/" # URL prefix for uploads
MEDIA_ROOT = BASE_DIR / "media" # where uploads are saved
SECURE_SSL_REDIRECT = True # send HTTP to HTTPS
SESSION_COOKIE_SECURE = True # session cookie over HTTPS only
CSRF_COOKIE_SECURE = True # CSRF cookie over HTTPS only
SECURE_HSTS_SECONDS = 31536000 # browsers use HTTPS for a year
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") # trust the proxy's HTTPS flagOfficial docsDeployment checklist (opens in a new tab)Settings reference (opens in a new tab)
Middleware
WebMiddleware wraps every request and response. Use it for things that apply site-wide: timing, headers, auth checks.
import time
class TimingMiddleware:
def __init__(self, get_response): # runs once at startup
self.get_response = get_response # the next layer (eventually the view)
def __call__(self, request): # runs on every request
start = time.perf_counter()
response = self.get_response(request) # call the view
ms = (time.perf_counter() - start) * 1000
response["Server-Timing"] = f"app;dur={ms:.1f}" # visible in browser devtools
return response
# settings.py
MIDDLEWARE = [..., "core.middleware.TimingMiddleware"] # register itOrder matters: requests pass through the list top to bottom, responses bottom to top.
Official docsMiddleware (opens in a new tab)Middleware order (opens in a new tab)
Signals
DataSignals let code react when something happens elsewhere, like a model being saved. Use them sparingly; explicit calls are easier to follow.
# accounts/signals.py
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=settings.AUTH_USER_MODEL) # after a user is saved
def create_profile(sender, instance, created, **kwargs):
if created: # only for new users
Profile.objects.create(user=instance)
# accounts/apps.py
from django.apps import AppConfig
class AccountsConfig(AppConfig):
name = "accounts"
def ready(self): # runs when Django starts
from . import signals # noqa # import so the receivers register| Signal | What it does |
|---|---|
pre_save / post_save | Before / after save() |
pre_delete / post_delete | Before / after a delete |
m2m_changed | Many-to-many links added or removed |
user_logged_in | A user just logged in |
queryset.update() and bulk_create() don't send save signals.
Official docsSignals (opens in a new tab)Built-in signals (opens in a new tab)
Caching
OpsStore expensive results so the next request reads them from memory instead of recomputing them.
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.redis.RedisCache", # built-in Redis backend
"LOCATION": "redis://127.0.0.1:6379/1",
}
}
from django.core.cache import cache
from django.views.decorators.cache import cache_page
cache.set("stats", data, timeout=300) # store for 5 minutes
cache.get("stats", default=None) # read, or None if missing / expired
cache.get_or_set("stats", compute_stats, 300) # read, or compute and store
cache.delete("stats") # invalidate
@cache_page(60 * 15) # cache the whole response for 15 min
def home(request):
...{% load cache %}
{% cache 600 sidebar request.user.pk %} {# cache this block 10 min, per user #}
...expensive fragment...
{% endcache %}Official docsCache framework (opens in a new tab)
Testing
OpsDjango's test runner gives each test a clean database and a fake browser (self.client) to call your views.
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
class PostTests(TestCase): # each test runs in a rolled-back transaction
@classmethod
def setUpTestData(cls): # create shared data once per class
cls.user = get_user_model().objects.create_user("ana", password="pw")
cls.post = Post.objects.create(
title="Hi", slug="hi", author=cls.user, status="pub",
)
def test_detail(self):
resp = self.client.get(reverse("blog:detail", args=["hi"])) # fake GET request
self.assertEqual(resp.status_code, 200) # page loads
self.assertContains(resp, "Hi") # text appears in the HTML
self.assertTemplateUsed(resp, "blog/detail.html")
def test_list_query_count(self):
self.client.force_login(self.user) # log in without a password
with self.assertNumQueries(3): # fail if an N+1 creeps in
self.client.get(reverse("blog:list"))
def test_on_commit(self):
with self.captureOnCommitCallbacks(execute=True): # run on_commit hooks in tests
...| Tool | What it does |
|---|---|
SimpleTestCase | No database; fastest |
TransactionTestCase | Real commits, for transaction behaviour |
LiveServerTestCase | Runs a server for browser tests |
RequestFactory | Build a request to call a view directly |
@override_settings(...) | Change settings for one test |
Official docsTesting tools (opens in a new tab)Writing and running tests (opens in a new tab)
Custom commands
OpsAdd your own manage.py commands for scripts and cron jobs that need your models and settings.
# blog/management/commands/publish_scheduled.py (file name = command name)
from django.core.management.base import BaseCommand
from django.utils import timezone
class Command(BaseCommand):
help = "Publish posts whose publish_at has passed" # shown in --help
def add_arguments(self, parser): # argparse options
parser.add_argument("--dry-run", action="store_true")
def handle(self, *args, **opts): # the command's body
qs = Post.objects.filter(status="draft", publish_at__lte=timezone.now())
n = qs.count() if opts["dry_run"] else qs.update(status="pub")
self.stdout.write(self.style.SUCCESS(f"{n} posts ready")) # green outputRun it with python manage.py publish_scheduled --dry-run. Both management/ and commands/ need an __init__.py.
Official docsCustom management commands (opens in a new tab)
DRF: setup & settings
APIDjango REST Framework builds JSON APIs on top of your models. DRF 3.18 supports Django 5.2, 6.0 and 6.1; upgrade to at least 3.18.2 for its security fixes.
pip install djangorestframework django-filter # API toolkit + filtering
pip install drf-spectacular # OpenAPI 3 schema + Swagger UIINSTALLED_APPS += ["rest_framework", "rest_framework.authtoken", "django_filters"]
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.SessionAuthentication", # browser / same site
"rest_framework.authentication.TokenAuthentication", # "Authorization: Token abc"
],
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticated", # locked down by default
],
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": 20, # ?page=2
"DEFAULT_FILTER_BACKENDS": [
"django_filters.rest_framework.DjangoFilterBackend", # ?status=pub
"rest_framework.filters.SearchFilter", # ?search=django
"rest_framework.filters.OrderingFilter", # ?ordering=-created
],
"DEFAULT_THROTTLE_CLASSES": [
"rest_framework.throttling.AnonRateThrottle",
"rest_framework.throttling.UserRateThrottle",
],
"DEFAULT_THROTTLE_RATES": {"anon": "60/min", "user": "1000/hour"},
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
}Official docsQuickstart (opens in a new tab)Settings (opens in a new tab)Release notes (opens in a new tab)
DRF: serializers
APIA serializer turns model instances into JSON and validates incoming JSON before saving. It is the API version of a ModelForm.
from rest_framework import serializers
class PostSerializer(serializers.ModelSerializer):
author = serializers.ReadOnlyField(source="author.username") # show a related value
comment_count = serializers.IntegerField(read_only=True) # from .annotate()
url = serializers.HyperlinkedIdentityField(view_name="post-detail", lookup_field="slug")
class Meta:
model = Post
fields = ["id", "url", "title", "slug", "body", "status",
"author", "comment_count", "created"]
read_only_fields = ["created"] # returned, never accepted
def validate_title(self, value): # one field
if "lorem" in value.lower():
raise serializers.ValidationError("Write a real title.")
return value
def validate(self, attrs): # across fields
if attrs.get("status") == "pub" and not attrs.get("body"):
raise serializers.ValidationError({"body": "Published posts need a body."})
return attrs
s = PostSerializer(data=request.data, context={"request": request})
s.is_valid(raise_exception=True) # 400 with error details
post = s.save(author=request.user) # create(); pass extra fields here
PostSerializer(post, data=payload, partial=True) # PATCH: update() on some fieldsOfficial docsSerializers (opens in a new tab)
DRF: views, viewsets & routers
APIA ModelViewSet gives you list, create, retrieve, update and delete in one class. A router writes the URLs for it.
from django.db.models import Count
from rest_framework import permissions, status, viewsets
from rest_framework.decorators import action, api_view
from rest_framework.response import Response
from rest_framework.routers import DefaultRouter
class PostViewSet(viewsets.ModelViewSet):
serializer_class = PostSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsAuthorOrReadOnly]
lookup_field = "slug" # /api/posts/hello-world/
filterset_fields = ["status"] # ?status=pub
search_fields = ["title", "body"] # ?search=
ordering_fields = ["created", "title"] # ?ordering=-created
def get_queryset(self): # always scope + optimise here
return (Post.objects.select_related("author")
.annotate(comment_count=Count("comments")))
def perform_create(self, serializer): # set server-side fields
serializer.save(author=self.request.user)
@action(detail=True, methods=["post"]) # POST /api/posts/{slug}/publish/
def publish(self, request, slug=None):
post = self.get_object() # runs object permissions
post.status = Post.Status.PUBLISHED
post.save(update_fields=["status"])
return Response({"status": "published"})
@api_view(["GET"]) # small function-based endpoint
def health(request):
return Response({"ok": True}, status=status.HTTP_200_OK)
router = DefaultRouter()
router.register("posts", PostViewSet, basename="post") # names: post-list, post-detail
urlpatterns = [path("api/", include(router.urls)), path("api/health/", health)]| Class or method | What it does |
|---|---|
APIView | Plain class with get(), post(); full control |
ListCreateAPIView | One endpoint: list + create |
RetrieveUpdateDestroyAPIView | One endpoint: detail + edit + delete (both in rest_framework.generics) |
ReadOnlyModelViewSet | Only list and retrieve |
get_serializer_class() | Override to use a lighter serializer for lists |
Official docsViewSets (opens in a new tab)Routers (opens in a new tab)
DRF: permissions & auth
APIAuthentication works out who is calling. Permissions decide what they may do. Throttles limit how often.
from rest_framework import permissions
class IsAuthorOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj): # runs in get_object()
if request.method in permissions.SAFE_METHODS: # GET, HEAD, OPTIONS
return True
return obj.author == request.user # only the author may edit
# urls.py: login endpoint that returns a token
from rest_framework.authtoken.views import obtain_auth_token
path("api/token/", obtain_auth_token) # POST username + password| Permission | What it does |
|---|---|
AllowAny | No checks; public endpoints |
IsAuthenticated | Any logged-in user |
IsAuthenticatedOrReadOnly | Anyone can read, users can write |
IsAdminUser | Only is_staff users |
DjangoModelPermissions | Uses Django's add / change / delete permissions |
A & B, A | B, ~A | Combine permission classes |
Filtering get_queryset() by user is what stops people seeing other people's rows. Object permissions alone don't filter list results.
Official docsAuthentication (opens in a new tab)Permissions (opens in a new tab)Throttling (opens in a new tab)
DRF: testing & commands
APITest endpoints with DRF's test client, and generate tokens and OpenAPI schemas from the command line.
from rest_framework import status
from rest_framework.test import APITestCase
class PostApiTests(APITestCase):
def test_create_requires_login(self):
resp = self.client.post("/api/posts/", {"title": "Hi"}, format="json")
self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # 401 with token-only auth
def test_create(self):
self.client.force_authenticate(user=self.user) # skip real auth in tests
resp = self.client.post("/api/posts/", {"title": "Hi", "slug": "hi"}, format="json")
self.assertEqual(resp.status_code, 201)
self.assertEqual(resp.json()["author"], self.user.username)python manage.py drf_create_token alice # print (or create) alice's token
python manage.py drf_create_token -r alice # replace it with a new one
python manage.py spectacular --color --file schema.yml # OpenAPI 3 file (drf-spectacular)
python manage.py spectacular --validate --fail-on-warn # CI: fail on schema problemsOfficial docsTesting (opens in a new tab)Schemas (opens in a new tab)
Email & MAILERS
New in 6.1Django 6.1 adds MAILERS: named email backends configured like DATABASES. The old EMAIL_* settings still work but are deprecated.
# settings.py (6.1+)
MAILERS = {
"default": {
"BACKEND": "django.core.mail.backends.smtp.EmailBackend",
"OPTIONS": {"host": "smtp.example.com", "port": 587, "use_tls": True,
"username": os.environ["SMTP_USER"], "password": os.environ["SMTP_PASS"]},
},
"console": {"BACKEND": "django.core.mail.backends.console.EmailBackend"}, # print to stdout
}
from django.core.mail import EmailMessage, send_mail
send_mail("Welcome", "Thanks for signing up.", None, ["[email protected]"]) # None = DEFAULT_FROM_EMAIL
send_mail("Digest", body, None, recipients, using="console") # pick a mailer
msg = EmailMessage("Invoice", "Attached.", to=["[email protected]"], bcc=["[email protected]"])
msg.attach_file("invoice.pdf") # add an attachment
msg.send()Test it with python manage.py sendtestemail [email protected] --using default. In tests, Django swaps in the locmem backend; check django.core.mail.outbox.
Official docsSending email (opens in a new tab)Django 6.1 release notes (opens in a new tab)
Deploy: app servers
Deployrunserver is for development only. In production a real server runs your wsgi.py (sync) or asgi.py (async, websockets) behind a reverse proxy.
pip install gunicorn uvicorn uvicorn-worker
# WSGI: classic sync Django
python -m gunicorn config.wsgi --bind 0.0.0.0:8000 --workers 3 --timeout 60
python -m gunicorn config.wsgi -k gthread --workers 2 --threads 4 # threads for I/O waits
# ASGI: async views, streaming, websockets
python -m uvicorn config.asgi:application --reload # dev
python -m gunicorn config.asgi:application -k uvicorn_worker.UvicornWorker --workers 4 # prod
# handy gunicorn flags
--max-requests 1000 --max-requests-jitter 100 # recycle workers (memory leaks)
--access-logfile - # access log to stdout
--forwarded-allow-ips="*" # trust proxy headers (behind a proxy only)Start with workers around 2 × CPU cores + 1 and tune by measuring. uvicorn.workers.UvicornWorker is deprecated; use the uvicorn-worker package.
Official docsHow to deploy Django (opens in a new tab)Gunicorn: how many workers (opens in a new tab)Uvicorn with Gunicorn (opens in a new tab)
Deploy: Docker
DeployA small production image and the Compose commands you run against it.
# Dockerfile
FROM python:3.13-slim
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 # no .pyc files, unbuffered logs
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt # cached layer while deps don't change
COPY . .
RUN DJANGO_SECRET_KEY=build-only DB_NAME=unused \
python manage.py collectstatic --noinput # dummy env: settings must import
RUN useradd --create-home app
USER app # don't run as root
EXPOSE 8000
CMD ["gunicorn", "config.wsgi", "--bind", "0.0.0.0:8000", "--workers", "3"]docker compose up -d --build # build and start in background
docker compose exec web python manage.py migrate # run a command in the running container
docker compose exec web python manage.py createsuperuser
docker compose run --rm web python manage.py test # throwaway container
docker compose logs -f web # follow logs
docker compose exec db psql -U postgres # open the database shell
docker compose down # stop (add -v to DELETE volumes and data)Official docsDockerfile reference (opens in a new tab)docker compose CLI (opens in a new tab)
Deploy: release commands
DeployWhat a CI pipeline or release script usually runs, in order.
python manage.py makemigrations --check --dry-run # 1. no model change left without a migration
python manage.py test --parallel auto # 2. tests
python manage.py check --deploy --fail-level WARNING # 3. production settings review
python manage.py collectstatic --noinput # 4. static files (or at image build)
python manage.py migrate --plan # 5. preview what will run
python manage.py migrate --noinput # 6. apply migrations
# 7. restart / roll the app servers
python manage.py migrate --check # health check: exit 1 if unapplied
python manage.py clearsessions # schedule daily with cronMake migrations backwards-compatible (add first, remove later) so old and new code can run side by side during a rolling deploy.
Official docsDeployment checklist (opens in a new tab)migrate (opens in a new tab)
Celery: setup & tasks
ToolsCelery runs tasks in separate worker processes through a broker such as Redis or RabbitMQ, with retries, scheduling and routing. Current stable: 5.7.
# config/celery.py
import os
from celery import Celery
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
app = Celery("config")
app.config_from_object("django.conf:settings", namespace="CELERY") # read CELERY_* settings
app.autodiscover_tasks() # find tasks.py in every installed app
# config/__init__.py
from .celery import app as celery_app # load Celery when Django starts
__all__ = ("celery_app",)
# settings.py
CELERY_BROKER_URL = "redis://localhost:6379/0"
CELERY_RESULT_BACKEND = "redis://localhost:6379/1"
CELERY_TASK_ACKS_LATE = True # re-run if a worker dies mid-task
# blog/tasks.py
from celery import shared_task
@shared_task(bind=True, autoretry_for=(ConnectionError,), retry_backoff=True, max_retries=5)
def send_welcome(self, user_id): # make tasks idempotent: they may run twice
...
send_welcome.delay(user.pk) # queue now
send_welcome.delay_on_commit(user.pk) # queue after the transaction commits (5.4+)
send_welcome.apply_async(args=[user.pk], countdown=60, queue="emails") # delay + routingOfficial docsFirst steps with Django (opens in a new tab)Tasks (opens in a new tab)
Celery: commands
ToolsStart workers and the scheduler, and inspect what is running. -A config points at the module that holds your Celery app.
celery -A config worker -l INFO # start a worker
celery -A config worker -l INFO -c 4 -Q emails,default # 4 processes, these queues only
celery -A config beat -l INFO # periodic task scheduler (run ONE)
celery -A config beat -l INFO \
--scheduler django_celery_beat.schedulers:DatabaseScheduler # schedules edited in admin
celery -A config inspect active # tasks running right now
celery -A config inspect registered # tasks each worker knows about
celery -A config status # which workers are alive
celery -A config purge # delete all waiting messages (careful)
celery -A config flower # web dashboard (pip install flower)Official docsWorkers guide (opens in a new tab)Periodic tasks (beat) (opens in a new tab)
django-debug-toolbar
ToolsA panel in the browser that shows every SQL query, template, cache call and signal for the current page. The fastest way to spot N+1 queries.
# pip install django-debug-toolbar (dev settings only)
INSTALLED_APPS += ["debug_toolbar"]
MIDDLEWARE = ["debug_toolbar.middleware.DebugToolbarMiddleware", *MIDDLEWARE] # as early as possible
INTERNAL_IPS = ["127.0.0.1"] # only show it to these IPs
# urls.py
from django.conf import settings
if settings.DEBUG:
from debug_toolbar.toolbar import debug_toolbar_urls
urlpatterns += debug_toolbar_urls() # mounts /__debug__/In Docker the request comes from the container network, not 127.0.0.1, so add that IP to INTERNAL_IPS.
Official docsInstallation (opens in a new tab)
django-extensions
ToolsA collection of extra manage.py commands. Add "django_extensions" to INSTALLED_APPS in development.
pip install django-extensions
python manage.py shell_plus --ipython # shell with models and helpers imported
python manage.py shell_plus --print-sql # show the SQL each query runs
python manage.py show_urls # every URL, its view and its name
python manage.py runserver_plus # Werkzeug debugger in the browser (pip install werkzeug)
python manage.py runserver_plus --cert-file local.crt # local HTTPS
python manage.py graph_models -a -o models.png # ER diagram (needs pygraphviz or pydot)
python manage.py print_settings DEBUG # value of one setting
python manage.py validate_templates # catch template syntax errors
python manage.py reset_db # drop and recreate the DB (dev only!)Since Django 5.2 the built-in shell also auto-imports models, so shell_plus is optional.
Official docsdjango-extensions docs (opens in a new tab)
Modern model features
5.xNewer model options that push work into the database: computed columns, database defaults and multi-column primary keys.
from django.db.models import F
from django.db.models.functions import Now
class OrderLine(models.Model):
pk = models.CompositePrimaryKey("order_id", "product_id") # 5.2: key on two columns
order = models.ForeignKey(Order, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.PROTECT)
qty = models.PositiveIntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
total = models.GeneratedField( # 5.0: column computed by the DB
expression=F("qty") * F("price"),
output_field=models.DecimalField(max_digits=12, decimal_places=2),
db_persist=True, # stored, not computed on read
)
created = models.DateTimeField(db_default=Now()) # 5.0: default set by the DBOfficial docsGeneratedField (opens in a new tab)db_default (opens in a new tab)Composite primary keys (opens in a new tab)
Template partials
New in 6.0Define a named fragment inside a template, reuse it, and render just that fragment from a view. Handy for htmx updates.
{# blog/list.html #}
{% partialdef post_card inline %} {# define it; "inline" also renders it here #}
<article><h2>{{ post.title }}</h2></article>
{% endpartialdef %}
{% for post in posts %}
{% partial post_card %} {# reuse it anywhere in this template #}
{% endfor %}return render(request, "blog/list.html#post_card", {"post": post}) # only the fragmentOfficial docsTemplate partials (opens in a new tab)partialdef tag (opens in a new tab)
Background tasks
New in 6.0A built-in way to define work that runs outside the request, like sending email. Django ships dev backends; production needs a worker backend from a package.
# settings.py
TASKS = {
"default": {"BACKEND": "django.tasks.backends.immediate.ImmediateBackend"} # runs inline (the default)
}
# "django.tasks.backends.dummy.DummyBackend" stores tasks but never runs them (tests)
# emails/tasks.py
from functools import partial
from django.tasks import task
@task(priority=0, queue_name="default") # module-level function only
def send_welcome(user_id):
user = User.objects.get(pk=user_id) # args must be JSON-safe: pass ids, not objects
...
result = send_welcome.enqueue(user_id=user.pk) # queue it; returns a result handle
result.status # READY, RUNNING, SUCCESSFUL, FAILED
await send_welcome.aenqueue(user_id=user.pk) # async version
transaction.on_commit(partial(send_welcome.enqueue, user_id=user.pk)) # only if the save commitsFor production, install a backend that comes with a worker, such as django-tasks-db (manage.py db_worker) or django-tasks-rq. For heavy or complex workloads, Celery is still the common choice (see the Celery card). Full walkthrough: Django 6 background tasks.
Official docsDjango's tasks framework (opens in a new tab)Task backends (opens in a new tab)
Content Security Policy
New in 6.0A CSP header tells browsers which scripts, styles and images your pages may load. It blocks most injected-script (XSS) attacks.
from django.utils.csp import CSP
MIDDLEWARE += ["django.middleware.csp.ContentSecurityPolicyMiddleware"] # sends the header
SECURE_CSP = {
"default-src": [CSP.SELF], # by default, only your own domain
"script-src": [CSP.SELF, CSP.NONCE], # scripts need your domain or a nonce
"img-src": [CSP.SELF, "https:"], # images from any HTTPS host
}
# add "django.template.context_processors.csp" to TEMPLATES for csp_nonce<script nonce="{{ csp_nonce }}">initCharts()</script> {# inline script allowed by nonce #}Start with SECURE_CSP_REPORT_ONLY to see what would break without blocking anything.
Official docsContent Security Policy (opens in a new tab)CSP how-to (opens in a new tab)
What changed recently
ReleasesWhat each recent release added, so you know what you can use.
| Release | Highlights |
|---|---|
| 6.1 | Field fetch modes (FETCH_PEERS), database-level on_delete, MAILERS setting, BitAnd/BitOr/BitXor for all databases, PostgreSQL 15+. Released Aug 2026. |
| 6.0 | Template partials, background tasks API, built-in CSP, modern email API, AsyncPaginator, BigAutoField as default primary key. Python 3.12+. Security fixes until April 2027. |
| 5.2 LTS | Composite primary keys, models auto-imported in shell. Supported until April 2028. |
| 5.1 | LoginRequiredMiddleware, {% querystring %} tag, PostgreSQL connection pools, SQLite connection options. |
| 5.0 | GeneratedField, db_default, form field groups, admin filter facets, enum classes as choices. |
From 2028 Django moves to yearly, calendar-versioned releases (Django 2028, 2029). Use the LTS release for long-lived projects. Upgrade one feature release at a time and fix deprecation warnings as you go (python -Wd manage.py test).
Official docsRelease notes (opens in a new tab)Upgrading Django (opens in a new tab)
Habits that save me time
TipsSmall rules I follow on every Django project.
- ▸Keep business logic in model methods or a
services.py, not in views. - ▸Use
F()for counters and balances so concurrent requests don't overwrite each other. - ▸Pass
update_fieldstosave()when you change one or two columns. - ▸Add a database constraint for every rule that must never break. Form validation alone isn't enough.
- ▸Name every URL and always build links with
reverseor{% url %}. - ▸Run
makemigrations --checkin CI so nobody forgets to commit a migration. - ▸Use
setUpTestDatainstead ofsetUpfor fixtures; tests run much faster.
Official docsConstraints (opens in a new tab)setUpTestData (opens in a new tab)update_fields (opens in a new tab)
Not affiliated with the Django Software Foundation. Django is a registered trademark of the DSF.