Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 77 ยท Practice and Review

Django Cheat Sheet

A one-page Django cheat sheet: manage.py commands, settings, URL converters, model fields, ORM lookups, template tags, form fields and test assertions.

This page packs the everyday parts of Django into one place: the commands you type, the settings you touch, the URL converters, model fields and ORM lookups you use, the template tags and form fields you reach for, and the assertions that make tests readable. Use it to refresh your memory while coding, while working through the exercises, or just before an interview.

Each section links to the lesson that explains the topic in depth. A few sections have a live editor that runs every item on the list, so you can see exactly what it returns. Examples assume a recent Django (5.x or 6.x); features tied to newer versions say so.

Commands

Run these as python manage.py <command> inside a project (or django-admin <command> with DJANGO_SETTINGS_MODULE set). See Installing Django and Your First Project.

Command What it does
django-admin startproject mysite . Create a project in the current folder
startapp blog Create an app skeleton
runserver [8080] Start the development server (optionally on another port)
makemigrations [app] Write migration files for model changes
makemigrations --merge Merge conflicting migration branches
makemigrations --check --dry-run Fail if models and migrations differ (useful in CI)
migrate [app [name]] Apply migrations (optionally up to one migration)
showmigrations List migrations and which are applied
sqlmigrate blog 0001 Print the SQL a migration would run
squashmigrations blog 0001 0005 Combine migrations into one
createsuperuser Create an admin user
changepassword NAME Change a user's password
shell Python shell with Django loaded
dbshell Open the database's own command-line client
test [-k NAME] [--parallel] Run the test suite
check [--deploy] Check the project; --deploy adds production checks
collectstatic Copy static files into STATIC_ROOT
dumpdata app.Model > data.json Export data as JSON
loaddata data.json Import data from a fixture
inspectdb Generate models from an existing database
makemessages -l de / compilemessages Extract and compile translations
diffsettings Show settings that differ from the defaults
flush Delete all data (keeps tables)

Custom commands live in app/management/commands/ (Custom Management Commands).

Settings

The ones you meet in almost every project (Projects, Apps and Settings):

Setting Purpose
SECRET_KEY Signing key; read from the environment, never commit it
DEBUG Detailed error pages; must be False in production
ALLOWED_HOSTS Host names the site may serve, e.g. ["example.com"]
INSTALLED_APPS Apps and Django contrib packages that are active
MIDDLEWARE Ordered list of request/response hooks
ROOT_URLCONF Dotted path of the root urls.py
TEMPLATES Template engines, directories and context processors
DATABASES Database connections (ENGINE, NAME, USER, ...)
AUTH_USER_MODEL Custom user model, e.g. "accounts.User"
LOGIN_URL, LOGIN_REDIRECT_URL, LOGOUT_REDIRECT_URL Where the auth views send people
STATIC_URL, STATIC_ROOT, STATICFILES_DIRS Static file URL, collection target and extra folders
MEDIA_URL, MEDIA_ROOT Uploaded files
DEFAULT_AUTO_FIELD Type of automatic primary keys
LANGUAGE_CODE, TIME_ZONE, USE_TZ Language, default time zone, timezone-aware datetimes
CACHES Cache backends
EMAIL_BACKEND How mail is sent (console, locmem, smtp)
CSRF_TRUSTED_ORIGINS Extra origins allowed for HTTPS form posts
SESSION_COOKIE_SECURE, CSRF_COOKIE_SECURE, SECURE_SSL_REDIRECT HTTPS hardening
Python
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": os.environ["DB_NAME"],
        "USER": os.environ["DB_USER"],
        "PASSWORD": os.environ["DB_PASSWORD"],
        "HOST": os.environ.get("DB_HOST", "localhost"),
    }
}

URLs and views

Path converters

Converter Matches Python type
<str:name> (default) any text without / str
<int:pk> digits int
<slug:slug> letters, digits, -, _ str
<uuid:token> a UUID uuid.UUID
<path:subpath> any text including / str

re_path(r"^archive/(?P<year>[0-9]{4})/$", view) handles patterns converters cannot. The editor resolves one URL for each kind so you can see the argument types (URL Routing).

Python Resolving every converter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Views, shortcuts and responses

Python
from django.http import HttpResponse, JsonResponse, Http404, HttpResponseRedirect
from django.shortcuts import render, redirect, get_object_or_404, get_list_or_404
from django.views.decorators.http import require_http_methods, require_POST, require_GET
from django.contrib.auth.decorators import login_required, permission_required

def detail(request, pk):
    post = get_object_or_404(Post, pk=pk)             # 404 if missing
    return render(request, "blog/detail.html", {"post": post})

return redirect("blog:detail", pk=3)                  # by URL name
return JsonResponse({"ok": True}, status=201)
return HttpResponse("Nope", status=403)
raise Http404("No such post")
Request attribute Holds
request.method "GET", "POST", ...
request.GET, request.POST QueryDict of query-string / form values
request.FILES Uploaded files
request.body Raw bytes (parse JSON yourself)
request.headers Case-insensitive headers (request.headers["User-Agent"])
request.COOKIES, request.session Cookies, session data
request.user Current user (or AnonymousUser)
request.path, request.get_full_path() URL path, path with query string
request.META WSGI environment (REMOTE_ADDR, ...)

Generic class-based views: TemplateView, RedirectView, ListView, DetailView, CreateView, UpdateView, DeleteView, FormView. Useful attributes: model, queryset, template_name, context_object_name, paginate_by, form_class, success_url, and the methods get_queryset(), get_context_data(), form_valid() (Generic Views).

Common status codes: 200 OK, 201 created, 204 no content, 301/302 redirects, 400 bad request, 401 unauthenticated, 403 forbidden, 404 not found, 405 method not allowed, 500 server error.

Models and fields

Field Notes
CharField(max_length=n) Short text
TextField() Long text
IntegerField, BigIntegerField, PositiveIntegerField Whole numbers
FloatField, DecimalField(max_digits, decimal_places) Approximate and exact decimals
BooleanField True/False
DateField, TimeField, DateTimeField Dates and times (auto_now_add, auto_now)
DurationField timedelta
EmailField, URLField, SlugField, UUIDField Validated text types
JSONField JSON data (pass default=dict, never {})
FileField, ImageField Uploads (ImageField needs Pillow)
ForeignKey(Other, on_delete=...) Many-to-one
OneToOneField One-to-one
ManyToManyField Many-to-many (optional through=)
GeneratedField Column computed by the database
Option Meaning
null=True Database allows NULL
blank=True Forms allow an empty value
default=value_or_callable Python-side default (use a callable for mutable values)
db_default=... Database-side default
unique=True, db_index=True Constraint and index
choices=... / TextChoices Fixed set of values
validators=[...] Extra validation
related_name="books" Name of the reverse accessor
help_text, verbose_name Documentation for forms and admin

on_delete choices: CASCADE (delete dependents), PROTECT (block deletion), RESTRICT (block unless the object is also being deleted through a cascade), SET_NULL, SET_DEFAULT, SET(value), DO_NOTHING.

Python
class Book(models.Model):
    class Format(models.TextChoices):
        PAPER = "P", "Paperback"
        EBOOK = "E", "E-book"

    title = models.CharField(max_length=120)
    author = models.ForeignKey("Author", on_delete=models.CASCADE, related_name="books")
    format = models.CharField(max_length=1, choices=Format, default=Format.PAPER)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["title"]
        constraints = [models.UniqueConstraint(fields=["title", "author"], name="unique_book")]
        indexes = [models.Index(fields=["created"])]

    def __str__(self):
        return self.title

See Models and Fields, Relationships and Custom Managers and Constraints.

The ORM

CRUD and common methods

Python
Book.objects.create(title="Dune", author=a)           # INSERT
Book.objects.bulk_create([Book(...), Book(...)])      # one INSERT
Book.objects.get(pk=1)                                # one row or DoesNotExist
Book.objects.get_or_create(title="Dune", defaults={...})   # (obj, created)
Book.objects.update_or_create(title="Dune", defaults={...})
Book.objects.filter(year__gte=2000)                   # queryset
Book.objects.exclude(author=a)
Book.objects.order_by("-year", "title")
Book.objects.all()[:10]                               # LIMIT 10
Book.objects.filter(pk=1).update(year=2001)           # UPDATE, returns row count
book.save(); book.delete()
Book.objects.filter(year__lt=1900).delete()
Returns a queryset (lazy) Returns something else (runs SQL now)
all, filter, exclude, order_by, distinct, reverse get, first, last, earliest, latest
select_related, prefetch_related, only, defer count, exists, aggregate, in_bulk
values, values_list, annotate, none, union create, bulk_create, bulk_update, update, delete

Field lookups

Use them as field__lookup=value in filter(), exclude() and get(). The editor runs each lookup on a small data set (Lookups, Q Objects and F Expressions).

Lookup Meaning
exact, iexact Equal (case-sensitive / insensitive)
contains, icontains Substring
startswith, istartswith, endswith, iendswith Prefix / suffix
in Value in a list
gt, gte, lt, lte Comparisons
range Between two values (inclusive)
isnull IS NULL / IS NOT NULL
regex, iregex Regular expression
year, month, day, week_day, date, hour Parts of dates and datetimes
related__field Follow a relation across tables
Python Every lookup on real rows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Q, F, aggregation and relations

Python
from django.db.models import Q, F, Count, Sum, Avg, Max, Min, Case, When, Value, Exists, OuterRef, Subquery

Book.objects.filter(Q(year__gt=2000) | Q(title__startswith="A"))   # OR
Book.objects.filter(~Q(author=a))                                  # NOT
Book.objects.filter(sold__gt=F("stock"))                           # compare columns
Book.objects.update(views=F("views") + 1)                          # atomic arithmetic

Book.objects.aggregate(avg=Avg("price"), top=Max("price"))         # -> dict
Author.objects.annotate(n=Count("books")).filter(n__gte=2)         # per-object value
Book.objects.values("year").annotate(n=Count("id")).order_by("year")   # GROUP BY
Book.objects.annotate(tier=Case(When(price__lt=20, then=Value("cheap")), default=Value("pricey")))
Author.objects.filter(Exists(Book.objects.filter(author=OuterRef("pk"), year__gt=2020)))

author.books.all()                  # reverse relation (related_name)
book.author                         # forward relation
Book.objects.filter(author__name="Ada")          # join in a filter
Book.objects.select_related("author")            # JOIN for forward FK / one-to-one
Author.objects.prefetch_related("books")         # 2nd query for reverse / M2M
Book.objects.only("title") ; Book.objects.defer("summary")
Book.objects.filter(...).distinct() ; qs.count() ; qs.exists()

More in Aggregation and Annotation, ORM Performance and Transactions and Concurrency (with transaction.atomic():, transaction.on_commit(func), select_for_update()).

Templates

Variables, filters and tags

DJANGO
{{ user.username }}   {{ items.0 }}   {{ mapping.key }}   {{ post.get_status_display }}
{{ value|default:"n/a" }}   {{ text|truncatewords:20 }}   {{ when|date:"Y-m-d" }}
{% url "blog:detail" post.pk %}   {% static "css/site.css" %}   {% csrf_token %}
{% extends "base.html" %}   {% block content %}...{% endblock %}   {% include "card.html" with post=p %}
{% load static %}   {% load humanize %}
Tag Use
{% if %} / {% elif %} / {% else %} / {% endif %} Conditions (and, or, not, in, ==, >)
{% for x in xs %} ... {% empty %} ... {% endfor %} Loops; forloop.counter, forloop.first, forloop.last
{% with total=a.b.c %} Name an expensive value
{% cycle "a" "b" %} Alternate values in a loop
{% firstof a b "x" %} First truthy value
{% widthratio v max 100 %} Scale a value to a width
{% autoescape off %} Disable escaping (use with care)
{% comment %}...{% endcomment %}, {# one line #} Comments
{% querystring page=2 %} Update query-string parameters (Django 5.1+)
{% csrf_token %} Hidden CSRF field inside POST forms
Common filters Result
upper, lower, title, capfirst Case changes
length, first, last, join:", ", slice:":3" Sequences
floatformat:2, add:5, divisibleby:2 Numbers
date:"Y-m-d", timesince, timeuntil Dates
default:"x", default_if_none:"x", yesno:"a,b" Fallbacks
truncatewords:10, truncatechars:40, slugify, pluralize Text
safe, escape, striptags, linebreaks, urlencode HTML handling

The editor renders one template that uses many of these (Django Templates, Template Inheritance, Custom Tags and Filters).

Python A template full of filters and tags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that {{ html }} printed &lt;b&gt;bold&lt;/b&gt; (autoescaped) while |safe kept the tag, and that person.skills.0 used the same dot syntax for a dictionary key, a list index and an attribute.

Forms

Python
class ContactForm(forms.Form):
    name = forms.CharField(max_length=50)
    email = forms.EmailField()

    def clean_name(self):                      # one field
        ...
    def clean(self):                           # across fields
        ...

form = ContactForm(request.POST)               # bound
if form.is_valid():
    data = form.cleaned_data
Form field Cleans to Common arguments
CharField str max_length, min_length, strip, widget
IntegerField int min_value, max_value
FloatField, DecimalField float, Decimal max_digits, decimal_places
BooleanField bool required=False for optional checkboxes
ChoiceField, MultipleChoiceField str, list choices
DateField, TimeField, DateTimeField date/time objects input_formats
EmailField, URLField, SlugField str Validated text
UUIDField, GenericIPAddressField UUID, str
FileField, ImageField uploaded file pass request.FILES
ModelChoiceField, ModelMultipleChoiceField model instance(s) queryset

Handy widgets: Textarea, PasswordInput, HiddenInput, RadioSelect, CheckboxSelectMultiple, Select, DateInput(attrs={"type": "date"}). Rendering: {{ form }}, {{ form.as_p }}, or field by field with {{ field.errors }}. A ModelForm adds class Meta: model = ...; fields = [...] and save(commit=False) (Django Forms, Form Validation, ModelForms).

Python What each form field returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Authentication, permissions and security

Python
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.contrib.auth.decorators import login_required, permission_required, user_passes_test
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin, UserPassesTestMixin

User = get_user_model()
user = User.objects.create_user("ada", "[email protected]", "s3cret-pass")
user = authenticate(request, username="ada", password="s3cret-pass")   # None on failure
login(request, user); logout(request)
user.has_perm("blog.add_post"); user.is_authenticated; user.is_staff; user.is_superuser
user.groups.add(group); user.user_permissions.add(permission)

Built-in auth URLs: include("django.contrib.auth.urls") gives login/, logout/, password_change/, password_reset/ and more (Users and Authentication, Permissions).

Protection How
CSRF {% csrf_token %} in every POST form; CsrfViewMiddleware enabled
XSS Keep autoescaping on; never mark user input as safe
SQL injection Use the ORM, or parameters (%s) with raw SQL
Clickjacking XFrameOptionsMiddleware (on by default)
HTTPS SECURE_SSL_REDIRECT, SECURE_HSTS_SECONDS, secure cookies
Secrets Environment variables; run check --deploy before every release

Middleware, signals, caching and email

Python
# Function middleware
def timing(get_response):
    def middleware(request):
        response = get_response(request)          # view and inner middleware run here
        response["X-Seen"] = "yes"
        return response
    return middleware

# Signals
@receiver(post_save, sender=Post)
def after_save(sender, instance, created, **kwargs): ...

# Cache
from django.core.cache import cache
cache.set("k", value, 60); cache.get("k"); cache.get_or_set("k", compute, 60); cache.delete("k")

# Email
from django.core.mail import send_mail
send_mail("Subject", "Body", "[email protected]", ["[email protected]"])

See Middleware, Signals, Caching and Logging, Email and Internationalization.

Testing

Python
from django.test import TestCase, SimpleTestCase, Client, RequestFactory, override_settings

class PostTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.post = Post.objects.create(title="Hello")

    def test_detail(self):
        response = self.client.get(reverse("blog:detail", args=[self.post.pk]))
        self.assertContains(response, "Hello")
Assertion Checks
assertEqual(a, b), assertTrue(x), assertIn(a, b) Plain Python assertions
assertContains(response, text, status_code=200) Status code and text present
assertNotContains(response, text) Text absent
assertRedirects(response, url) Redirect target and the target's status code
assertTemplateUsed(response, "x.html") Template rendered
assertJSONEqual(raw, data) JSON equality ignoring key order
assertFormError(form, "field", "message") Error on a form field
assertQuerySetEqual(qs, [objs]) Queryset contents
assertNumQueries(n) (context manager) Exactly n SQL queries
assertRaises(Exc) / assertRaisesMessage(Exc, "text") Exception raised
assertLogs("logger", level="WARNING") A log record was emitted

Client helpers: client.get(url, {"q": "x"}), client.post(url, data), client.post(url, json, content_type="application/json"), client.login(username=..., password=...), client.force_login(user). Base classes: SimpleTestCase (no database), TestCase (transaction per test), TransactionTestCase. Run with python manage.py test blog.tests.PostTests.test_detail (Testing Django Apps).

Python A tour of test assertions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Seven tests, each exercising a different assertion, all pass. Change an expected value (for example {"notes": 2}) and rerun to see how a failure reads.

Quick decisions

  • Need to read related rows without N+1? select_related for forward foreign keys, prefetch_related for reverse and many-to-many.
  • Need atomic counters or column-to-column comparisons? F().
  • Need OR / NOT conditions? Q().
  • Need a number per row or per group? annotate(); a single total? aggregate().
  • Need all-or-nothing writes? transaction.atomic().
  • Need code that runs on every request? Middleware. A reaction to a model event you do not own? A signal. Your own business rule? A plain function or model method.
  • Need a rule across two form fields? Form.clean(); one field? clean_<field>().

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which URL converter matches text that may contain slashes?

    str matches any non-empty text without a slash. path also accepts slashes, which is what you need for nested file paths.
  2. 2. What does assertNumQueries(1) verify?

    assertNumQueries is a context manager that counts the SQL queries executed inside the with block and fails if the number differs.
  3. 3. Which lookup keeps rows whose subtitle column is NULL?

    isnull=True generates IS NULL. (exact=None is also translated to IS NULL by Django, but isnull states the intent clearly.)
  4. 4. In a template, what does {{ person.skills.0 }} do?

    The dot tries a dictionary key, an attribute and then an index, so one syntax covers dictionaries, objects and lists.

Summary

  • manage.py commands drive the workflow: makemigrations and migrate for the schema, test and check --deploy for quality, collectstatic for deployment.
  • Path converters (int, str, slug, uuid, path) pass typed arguments to views; name your URLs and use reverse().
  • Model fields, null/blank/default options and on_delete choices define your schema; remember default=list for JSON.
  • ORM lookups use field__lookup=value; combine them with Q, F, annotate and aggregate, and optimize with select_related and prefetch_related.
  • Templates use {{ variable|filter }} and {% tag %}; variables are escaped unless you mark them safe.
  • Form fields clean raw strings into Python types and collect errors; tests use TestCase, the Client and focused assertions.

Back to the start of the track: Django Introduction.