Django Cheatsheet — Complete Quick Reference (2026)
DodaTech
Updated 2026-06-20
3 min read
In this tutorial, you'll learn about Django Cheatsheet. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Django is a high-level Python web framework that follows the "batteries-included" philosophy — providing ORM, admin, authentication, forms, and templating out of the box.
Models
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
tags = models.ManyToManyField('Tag')
published = models.BooleanField(default=False)
class Meta:
ordering = ['-created']
indexes = [models.Index(fields=['slug'])]
def __str__(self):
return self.title
Common Field Types
| Field | Parameters |
|---|---|
CharField |
max_length, choices, default |
TextField |
max_length (optional) |
IntegerField |
default, choices |
FloatField |
|
BooleanField |
default, null |
DateField / DateTimeField |
auto_now, auto_now_add |
EmailField |
|
URLField |
|
FileField / ImageField |
upload_to |
ForeignKey |
to, on_delete, related_name |
ManyToManyField |
to, through, related_name |
OneToOneField |
to, on_delete |
ORM Queries
# CRUD
Post.objects.create(title="Hello", slug="hello")
post = Post.objects.get(id=1)
post.title = "Updated"; post.save()
post.delete()
# filtering
Post.objects.filter(published=True)
Post.objects.exclude(author__username='admin')
Post.objects.filter(created__year=2026, tags__name='python')
# chaining (lazy)
qs = Post.objects.filter(published=True).order_by('-created')[:10]
# aggregation
from django.db.models import Count, Avg
Post.objects.aggregate(Count('id'), Avg('author__id'))
# select_related / prefetch_related (N+1 fix)
Post.objects.select_related('author').all()
Post.objects.prefetch_related('tags').all()
Views
# Function-based view
from django.shortcuts import render, get_object_or_404
def post_detail(request, slug):
post = get_object_or_404(Post, slug=slug)
return render(request, 'blog/detail.html', {'post': post})
# Class-based view (generic)
from django.views.generic import ListView, DetailView
class PostListView(ListView):
model = Post
template_name = 'blog/list.html'
context_object_name = 'posts'
paginate_by = 20
URLs
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.PostListView.as_view(), name='post_list'),
path('post/<slug:slug>/', views.post_detail, name='post_detail'),
path('api/', include('api.urls')),
]
Templates
{% extends "base.html" %}
{% block content %}
{% for post in posts %}
<h2><a href="{% url 'post_detail' post.slug %}">{{ post.title }}</a></h2>
<p>{{ post.body|truncatewords:50 }}</p>
{% empty %}
<p>No posts yet.</p>
{% endfor %}
{% endblock %}
Forms
from django import forms
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'slug', 'body', 'published']
widgets = {
'body': forms.Textarea(attrs={'rows': 10}),
}
# in view
def create_post(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
form.save()
return redirect('post_list')
else:
form = PostForm()
return render(request, 'blog/form.html', {'form': form})
Admin Customization
from django.contrib import admin
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'author', 'published', 'created']
list_filter = ['published', 'created']
search_fields = ['title', 'body']
prepopulated_fields = {'slug': ('title',)}
autocomplete_fields = ['author']
date_hierarchy = 'created'
Middleware
# settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# custom
class MyMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# before view
response = self.get_response(request)
# after view
return response
Management Commands
python manage.py startapp blog
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py collectstatic
python manage.py shell
python manage.py test
Must-Know Items
- Always use
get_object_or_404()instead ofModel.objects.get()in views - Use
select_related(FK, O2O) andprefetch_related(M2M, reverse FK) to prevent N+1 queries - Django migrations are auto-generated from model changes — never edit them manually
DEBUG=Falsein production;ALLOWED_HOSTSmust be setSECRET_KEYmust be kept secret — use environment variables- Use
python-dotenvordjango-environfor env management manage.py check --deploysurfaces production security warnings- Class-based views reduce boilerplate — use them for standard CRUD
See full Django tutorials for building production web applications.
← Previous
Bash Scripting Cheatsheet — Complete Quick Reference (2026)
Next →
FastAPI Cheatsheet — Complete Quick Reference (2026)
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro