Skip to main content
Quick Reference

Django Cheatsheet

Django 5 on one page — the project layout, settings and URLs, models, the ORM, function views, templates, forms, the admin, tests, and the traps that show up in interviews.

10 sections 10 tables 17 code snippets

Project & commands

Create and run

django-admin startproject shop
python manage.py startapp books
python manage.py makemigrations
python manage.py migrate
python manage.py runserver

What each command does

startproject   settings, urls, wsgi
startapp      models, views, admin
makemigrations  writes a migration file
migrate         applies it to the database
runserver       http://127.0.0.1:8000

Where code lives

PathRole
shop/settings.pyInstalled apps, database, debug, hosts
shop/urls.pyThe root URL table. Include each app from here
books/models.pyTables
books/views.pyWhat a request does
books/templates/books/HTML. The extra books/ folder keeps names unique

This page is Django 5. A new app does nothing until its dotted path is in INSTALLED_APPS.

Settings & URLs

Production settings worth setting

SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
DEBUG = False
ALLOWED_HOSTS = ["shop.example.com"]

A named route

urlpatterns = [
    path("books/", views.book_list, name="book-list"),
    path("books/<int:pk>/", views.book_detail, name="book-detail"),
]

Routing pieces

PieceMeaning
path()A URL pattern. Prefer it over re_path unless you need a real regex
<int:pk>A converter. Also str, slug, uuid
name="book-list"Used by redirect and {% url "book-list" %}. Do not hard-code the path
include("books.urls")Mounts an app under a prefix
Trailing slashDjango redirects /books to /books/ when APPEND_SLASH is on

Models

A table

class Book(models.Model):
    title = models.CharField(max_length=200)
    pages = models.PositiveIntegerField()
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created"]

    def __str__(self):
        return self.title

Field choices

FieldUse
CharFieldShort text. max_length is required. Use blank=True for optional, not null=True
TextFieldLong text
ForeignKeyon_delete is required. related_name is the reverse name
CASCADEDelete the children when the parent goes
auto_now_addSet once, on insert. auto_now updates on every save
Meta.orderingThe default order. A minus sign sorts descending

Editing a model does not change the database. Run makemigrations, read the file, then migrate. Commit the migration.

Queries

Read and write

Book.objects.create(title="Django", pages=300)
Book.objects.filter(pages__gte=100)
Book.objects.get(pk=pk)

Follow a relation

books = Book.objects.prefetch_related("reviews")
for book in books:
    for review in book.reviews.all():
        print(review.rating)

Query methods

CallResult
filterA queryset. Empty is not an error
getOne row. Raises if there are zero or many
get_object_or_404get that becomes a 404 response
excludeThe opposite of filter
select_relatedA SQL join for a foreign key or one-to-one
prefetch_relatedA second query for a reverse relation or many-to-many

A queryset is lazy. It hits the database when you loop, slice, or call len. Build it fully, then evaluate it once.

Function views

List

def book_list(request):
    books = Book.objects.all()
    return render(request, "books/list.html", {"books": books})

Create

@login_required
def book_create(request):
    form = BookForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect("book-list")
    return render(request, "books/form.html", {"form": form})

What the view returns

HelperWhen
renderA template plus a context dict
redirectAfter a successful POST, so a refresh does not submit again
get_object_or_404(Book, pk=pk)A missing row is a 404, not a 500
@login_requiredAnonymous users go to LOGIN_URL
request.userThe logged-in user, or AnonymousUser

request.POST or None keeps a GET form unbound. An unbound form does not show “this field is required” before the user has typed anything.

Templates

A list page

{% extends "base.html" %}
{% block content %}
<ul>
  {% for book in books %}
    <li>{{ book.title }}</li>
  {% empty %}
    <li>No books yet</li>
  {% endfor %}
</ul>
{% endblock %}

Template tags

TagMeaning
{{ book.title }}Print a value. HTML is escaped
{% for %} / {% empty %}Loop. empty runs when the list has no rows
{% if %}A condition. There is no else if; use {% elif %}
{% url "book-list" %}The path for a named route
{% csrf_token %}Required inside every POST form
{{ form.as_p }}Renders the fields as paragraphs

|safe marks a string as HTML. Use it only for markup you wrote. A book title belongs in {{ book.title }}, which escapes it.

Forms

A model form

class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ["title", "pages"]

The template

<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Save</button>
</form>

Form rules

RuleWhy
fields = ["title", "pages"]Never use fields = "__all__" on a form a user posts
is_valid()Runs the field checks. cleaned_data exists only after this returns true
save()Writes the model. save(commit=False) lets you set the author first
blank=TrueThe form may omit the value. null=True is the database, not the form
CSRF cookieA 403 on POST almost always means the token or the cookie is missing

Admin & auth

Register a model

@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    list_display = ["title", "pages"]
    search_fields = ["title"]

A superuser

python manage.py createsuperuser
# then open /admin/

Auth pieces

PieceRole
django.contrib.adminThe staff UI. It is not your public site
django.contrib.authUsers, groups, and passwords
AUTH_USER_MODELSet a custom user before the first migrate. Changing it later is a project rewrite
@login_requiredA view for signed-in users
is_staffWho may open /admin/

Passwords are hashed. Read request.user and the auth helpers. Do not store a password column of your own.

Tests

A view test

class BookViewTests(TestCase):
    def test_list_is_empty(self):
        response = self.client.get("/books/")
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "No books yet")

What the test tools do

ToolBehavior
TestCaseEach test runs in a transaction that is rolled back
self.clientCalls your URLs without a browser
assertContainsStatus 200, and the text is in the body
force_login(user)Skips the login form when the view needs a user
python manage.py testLooks for tests.py and test_*.py

Create rows with the ORM inside the test. TestCase is not looking at your development database.

Interview traps

Traps worth memorising

TrapWhat happensPrefer
App missing from INSTALLED_APPSThe model is invisible. migrate skips itAdd the app, then migrate
Model edited, no migrationThe database still has the old columnsmakemigrations and commit the file
DEBUG = True on the serverTracebacks and settings leak to visitorsDEBUG = False and a real ALLOWED_HOSTS
POST form without {% csrf_token %}403 ForbiddenThe token inside the form
objects.get for a pageA missing row is a 500get_object_or_404
Looping book.reviews.allOne query per bookprefetch_related("reviews")
null=True on a CharFieldThe column holds both NULL and an empty stringblank=True only
fields = "__all__"A new model field becomes user-writableAn explicit list
{{ title|safe }} on user textStored HTML runs in the page{{ title }}
Hard-coded /books/ in a templateRenaming the route leaves broken links{% url "book-list" %}
Custom user model after launchEvery foreign key already points at auth.UserSet AUTH_USER_MODEL before the first migrate
SECRET_KEY in gitAnyone with the repo can forge sessionsAn environment variable

One query for the children

books = Book.objects.prefetch_related("reviews")

A missing book is a 404

book = get_object_or_404(Book, pk=pk)

How to use this page: start a project, add books to INSTALLED_APPS, and make one model. Migrate, register it in the admin, then add a list view whose template uses {% csrf_token %} on the create form.