By Bogdan Sandu · Updated September 21, 2026
What Is a Django Cheat Sheet?
A Django cheat sheet is a condensed reference that lists the framework's commands, model syntax, and configuration patterns in one place.
Developers reach for it in the middle of real software development, not while working through a tutorial line by line.
What it typically covers:
- Command syntax for manage.py and django-admin
- Model field types and relationship shortcuts
- URL routing patterns and view signatures
- Template tags, filters, and settings blocks
It is not a replacement for Django's official documentation on edge cases.
It skips the reasoning behind a feature and jumps straight to the syntax, which is exactly what you want when you already know what you're building.
Django itself is a high-level Python framework for back-end development, built around the Model-View-Template pattern.
Adrian Holovaty and Simon Willison built it in 2003 at the Lawrence Journal-World newspaper, where fast newsroom publishing shaped its focus on speed and a strong admin interface.
Django is now maintained by the Django Software Foundation and distributed through PyPI, with a release roughly every eight months.
Setting Up a Django Project Environment
JetBrains' 2026 State of Django survey found 63% of Django developers still manage environments with venv, while uv, released in 2024, has already reached 43% adoption.
Both tools isolate a project's dependencies from whatever else is installed on the machine.
Setup sequence:
- Create and activate a virtual environment for the project
- Install Django with pip and freeze the versions into requirements.txt
- Run django-admin startproject to scaffold the project folder
- Run manage.py startapp for each app inside the project
- Start the local server with manage.py runserver to confirm everything loads
This sequence lays out a codebase you can navigate later without guessing where settings or URLs live.
It is also the natural point to run git init, especially if a git cheat sheet is already open in another tab.
Disqus built its comment platform on Django and leaned on this same fast bootstrap to ship its first version quickly.
Essential manage.py Commands
Django's command line tool wraps the most common project tasks into a single manage.py entry point.
| Command | Category | What it does |
| startproject | Project | Scaffolds a new Django project folder |
| startapp | Project | Creates a new app inside the project |
| makemigrations | Database | Writes migration files from model changes |
| migrate | Database | Applies migrations to the database schema |
Beyond that core four, a handful of commands come up constantly once a project is running.
Everyday commands:
- runserver: starts the local development server, usually on port 8000
- createsuperuser: sets up an admin account for the Django admin site
- shell: opens the interactive Django shell with your models already loaded
- collectstatic: gathers static files into one directory for deployment
- test: runs the project's test suite
Running manage.py help lists every command available for the Django version currently installed.
Django Model Field Types and Migrations
Model fields define what a database column stores and how Django validates it before saving.
Each field type maps to a specific column type in the underlying database.
Common Field Types
Core field types:
- CharField for short text with a required max_length
- IntegerField for whole numbers
- DateTimeField for timestamps
- BooleanField for true or false flags
Relationship fields connect one model to another instead of storing a plain value.
| Field | Relationship | Typical use |
| ForeignKey | Many to one | Order belongs to one customer |
| ManyToManyField | Many to many | Article has many tags |
| OneToOneField | One to one | Profile extends the User model |
Defining validation once at the field level follows the same software development principles that keep a Django codebase from repeating itself.
Running and Reversing Migrations
makemigrations compares your models against the last recorded state and writes the difference to a new, numbered file.
- Edit a model in models.py
- Run python manage.py makemigrations to generate the migration file
- Run python manage.py migrate to apply it to the database
- Run python manage.py migrate app_name 0002 to roll the schema back to an earlier migration
Instagram's engineering team has written publicly about scaling its Django ORM layer against a sharded Postgres backend as its user base grew.
Which Database Backend Fits Your Django Project
Django ships with support for four database backends, and the choice mostly comes down to how the app will actually be used.
JetBrains' 2026 State of Django survey found PostgreSQL has been the top choice for 76 to 79% of Django developers for five straight years.
| Database | Default use | Concurrency | Production ready |
| SQLite | Local development, small tools | One writer at a time | Rarely, file-based limits |
| PostgreSQL | General production workloads | Strong concurrent writes | Yes, default recommendation |
| MySQL | Existing MySQL infrastructure | Good with tuning | Yes, widely used |
| MariaDB | MySQL-compatible deployments | Good with tuning | Yes, smaller footprint |
The 2025 edition of the same survey put SQLite usage at 42%, MySQL at 27%, and MariaDB at 9% among Django developers, mostly running alongside PostgreSQL rather than replacing it.
Switching backends later usually means updating one setting, not rewriting models, since the Django ORM abstracts the SQL dialect away.
Postgres also supports the kind of software scalability a growing Django app eventually needs, including native JSON fields and full-text search.
Pinterest ran its early back end on Django paired with MySQL before rebuilding its data layer for scale.
Anyone running raw queries against these databases for admin reports will get more out of a SQL cheat sheet than out of the ORM documentation alone.
Django URL Routing and View Patterns
Django matches an incoming request to a view by walking through a list of URL patterns in order.
The first pattern that matches wins, so pattern order inside urls.py matters.
path() and re_path() Syntax
path() handles the common cases:
- Static routes like path('about/', views.about)
- Typed parameters like path('post/<int:post_id>/', views.detail)
- Slug and string converters for readable URLs
re_path() drops down to full regular expressions for patterns path() cannot express.
Most Django projects use path() almost exclusively and reserve re_path() for legacy URL schemes carried over from another codebase.
include() and URL Namespacing
Large projects rarely define every route in one urls.py file.
include() lets the root URLconf hand off a whole block of routes to an app's own urls.py.
Why namespacing matters: two apps can both define a route called detail without colliding, as long as each app sets its own app_name.
- reverse('blog:detail', args=[post.id]) resolves a namespaced URL in Python code
- {% url 'blog:detail' post.id %} does the same thing inside a template
Class-Based Views vs Function-Based Views
Both approaches satisfy the same contract: accept a request, return a response.
The difference shows up in how much boilerplate you write and how easy the view is to extend later.
Function-based views:
- Explicit, top-to-bottom control flow
- Faster to write for a one-off page
- Harder to reuse across similar views without copy-pasting
Class-based views:
- Built-in generics like ListView and DetailView cut boilerplate for CRUD pages
- Easier to extend through mixins and inheritance
- Requires knowing which method to override, which slows down debugging at first
Rewriting a function-based view as a class-based one later is a common piece of code refactoring as a Django app grows past its first few pages.
Neither option is wrong on its own, and most production codebases mix both depending on how much a given page needs to do.
Choosing case by case, rather than committing the whole project to one style, lines up with general software development best practices around not over-engineering simple pages.
Django Template Tags and Filters Reference
Django templates render Python data inside HTML using a restricted set of tags and filters.
The restriction is deliberate: template logic stays simple, and real logic stays in views.
| Tag | Purpose | Example |
| {% for %} | Loops over a queryset or list | {% for post in posts %} |
| {% if %} | Conditional rendering | {% if user.is_authenticated %} |
| {% block %} | Marks an overridable section | {% block content %} |
| {% extends %} | Inherits a parent template | {% extends "base.html" %} |
Filters transform a value inline, right where it gets displayed.
- |date formats a datetime object
- |safe skips HTML autoescaping for trusted content
- |length returns the size of a list or string
- |default shows a fallback when a value is empty
Template inheritance keeps a project's front-end development work in one base layout instead of duplicating a header and footer across pages.
Mozilla's Add-ons site runs on Django and renders its pages server-side rather than through a separate JavaScript front end.
JetBrains' 2026 State of Django survey found Django's built-in template engine has held steady at around 80% adoption even as HTMX and Alpine.js have grown around it.
Customizing the Django Admin and Authentication
Django's admin site is generated automatically from your models, and most customization happens by writing a ModelAdmin class.
Authentication is built on the same app, sharing the same User model and permission system.
ModelAdmin Customization Options
Common ModelAdmin options:
- list_display shows chosen fields as table columns
- search_fields adds a search box across the fields listed
- list_filter adds a sidebar filter for the fields listed
- inlines edits related objects on the same page as the parent
Registering a model takes two lines: admin.site.register(Model, ModelAdmin).
National Geographic uses Django's admin tooling to manage editorial content across its site.
Authentication and Permissions
Django's auth app ships with a User model, login views, and a permission system out of the box.
| Component | What it controls |
| User model | Username, password hash, email, active status |
| Groups | Reusable sets of permissions |
| Permissions | Per-model add, change, delete, view rights |
Session-based login covers most server-rendered sites, but an API consumed by a mobile app usually needs token-based authentication instead.
Configuring Django Settings for Development and Production
Django loads all configuration from one settings module, and that module needs to behave differently depending on the environment.
Splitting settings into a base file plus dev and prod overrides keeps secrets and debug flags from leaking into the wrong place.
Development Settings
Typical development flags:
- DEBUG = True for detailed error pages
- ALLOWED_HOSTS left open or set to localhost
- SQLite as the default database
- Console email backend instead of a real mail server
None of these settings belong in a live deployment, even temporarily.
Production Settings
DEBUG = True in a live deployment exposes stack traces, installed packages, and settings values to anyone who triggers an error.
| Setting | Development | Production |
| DEBUG | True | False |
| ALLOWED_HOSTS | Open or empty | Explicit domain list |
| Database | SQLite | PostgreSQL or MySQL |
Keeping close environment parity between staging and production catches configuration bugs before real users do.
A production environment also needs a real secret key pulled from an environment variable, never hardcoded in settings.py.
Choosing a Django Version (5.2 LTS vs 6.0 vs 6.1)
Django ships a feature release roughly every eight months, with an LTS release every two years that gets three years of security support.
Picking the wrong one for a cheat sheet means half the commands are already outdated.
| Version | Type | Support window |
| 4.2 | LTS | Ended April 2026, upgrade now |
| 5.2 | LTS | Ends April 2028 |
| 6.0 | Standard | Bug fixes ended with 6.1, security fixes until 6.2 ships |
| 6.1 | Standard | Current release, bug and security fixes until 6.2 ships |
Django's own release notes confirm 5.2 is designated long-term support and will receive security updates for at least three years after release.
JetBrains' 2026 survey found 43% of respondents were already running Django 6.0 within months of its release, well ahead of the usual upgrade curve.
Version numbers follow semantic versioning, so a jump from 5.2 to 6.0 can carry breaking changes that a 5.1-to-5.2 update would not.
Testing and Deploying Django Applications
Testing and deployment sit outside the core framework, but Django ships enough tooling to handle both without extra setup.
Testing Commands and Tools
manage.py test runs Django's built-in test runner against any TestCase classes in the project.
- pytest-django replaces the built-in runner with pytest's fixtures and plugins
- Django Debug Toolbar profiles queries and template rendering time in the browser
- coverage.py reports which lines of code the test suite actually exercises
Automated unit testing catches a broken model method before it reaches a deployed branch.
Deployment Stack Options
The Django Developers Survey found 45% of Django developers use GitHub Actions for continuous integration, and 39% implement infrastructure as code (JetBrains, 2024).
| Component | Role | Common choice |
| Application server | Runs the Django process | Gunicorn |
| Web server | Handles TLS and static files | Nginx |
| Static hosting | Serves collected static files | Whitenoise or a CDN |
Nginx typically sits in front of Gunicorn as a reverse proxy, handling TLS termination before passing requests to Django.
Dropbox has used Django to power parts of its web application, one of several large-scale deployments that show the framework holding up past side-project scale.
When a Django Cheat Sheet Is Not Enough
A cheat sheet covers syntax, not architecture, and some problems only surface once a project outgrows the basics.
Where the syntax alone runs out:
- Migration conflicts from two developers editing the same model at once
- CSRF and session errors that trace back to a settings misconfiguration, not the view code
- Static file 404s in production despite collectstatic running without errors
JetBrains' 2024 State of Django survey found 61% of Django developers already use asynchronous technologies, a layer that a syntax reference barely touches.
Async views, Celery task queues, Django Channels, and a full RESTful API built with Django REST Framework all need their own dedicated references.
The same goes for packaging a project with containerization tools like Docker, which sits outside anything manage.py handles directly.
At that point, a cheat sheet is still useful for the commands typed daily. It just stops being the only document open on the screen.
FAQ on Django
What is Django used for?
Django is a Python web framework for building database backed sites and APIs: content sites, SaaS products, internal tools, e-commerce backends, and JSON APIs for mobile and single page apps through Django REST Framework. It ships with an ORM, an admin interface, authentication, forms, templates, caching, a test client and since 6.0 a background tasks framework, so most of the plumbing is already written and audited.
What is the difference between a function based view and a class based view in Django?
A function based view is a plain function that takes a request and returns a response, and it is the clearest choice for logic that does not fit a pattern. A class based view is a class whose methods handle each HTTP verb, and Django ships generic ones such as ListView, DetailView, CreateView and UpdateView that implement the common pages in a few lines by overriding attributes. Use generic class based views for standard CRUD pages and function based views for everything unusual.
What is the N+1 query problem in Django and how do I fix it?
N+1 happens when you load a QuerySet and then access a related object on each row inside a loop, so 100 books with their authors run 101 queries. Fix it with select_related for foreign keys and one to one relations, which joins in one query, and prefetch_related for many to many and reverse relations, which runs one extra query. Django 6.1 adds QuerySet.fetch_mode(FETCH_PEERS), which fetches the missing relation for every instance in the QuerySet the first time any of them touches it.
Which Django version should I use?
Django 6.1, released August 5, 2026, is the current release, and Django 5.2 is the long term support release with security fixes until April 2028. New projects should start on 6.1 with Python 3.12 or newer. Teams that need a slow upgrade cadence stay on 5.2 LTS, which is why this cheat sheet marks every feature that needs 6.0 or newer and has a switch to hide them. Django 4.2 reached end of life in April 2026 and should be upgraded.
What changed in Django 6.0 and 6.1?
Django 6.0, released December 3, 2025, added a built in Content Security Policy middleware, template partials with the partialdef and partial tags, a background tasks framework in django.tasks, a modern email API based on Python's email.message, and made BigAutoField the default primary key. It requires Python 3.12 or newer. Django 6.1, released August 5, 2026, added QuerySet fetch modes to prevent N+1 queries, database level delete options such as DB_CASCADE on foreign keys, the MAILERS setting for several email backends, UUID7 database functions, and announced calendar versioning, so the release after 6.2 will be called Django 2028.
How do I deploy a Django application?
Set DEBUG to False and fill ALLOWED_HOSTS, read SECRET_KEY and database credentials from environment variables, run manage.py check with the deploy flag, run migrate and collectstatic, and serve the app with Gunicorn or Uvicorn behind Nginx, or with WhiteNoise handling static files. Use PostgreSQL rather than SQLite, run manage.py test in CI, and keep a process manager or container orchestrator restarting the workers. Platforms such as Railway, Render, Fly.io and Heroku automate most of this.
Is this Django cheat sheet up to date?
Yes. It was written for Django 5.2 LTS, 6.0 and 6.1 and checked against the Django 6.1 release notes and documentation on September 21, 2026. Every snippet that needs Django 6.0 or newer carries a version badge, the 5.2 LTS mode switch in the toolbar hides those snippets, and the date in the article byline changes with every revision.
Can I download this Django cheat sheet as a PDF?
Yes. The page has a print stylesheet, so your browser's print command with Save as PDF produces a clean copy: the dark theme switches to a print palette, every expected output and explanation is expanded, and the search box, navigation and footer are left out. Collapse the sections you do not need first, or run a search, and only what is still visible is printed.