AI Generate Django docs instantly

Django Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

Models

4 snippets

Django ORM model definitions

Basic Model

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    published = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']

Relationships

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    tags = models.ManyToManyField(Tag, blank=True)

Manager

class PublishedManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(published=True)

class Post(models.Model):
    objects = models.Manager()
    published = PublishedManager()

Migrations

python manage.py makemigrations
python manage.py migrate
python manage.py showmigrations
python manage.py sqlmigrate app_name 0001

Views

3 snippets

Function and class-based views

Function View

from django.shortcuts import render, get_object_or_404

def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    return render(request, 'posts/detail.html', {'post': post})

Class-Based View

from django.views.generic import ListView, DetailView, CreateView

class PostList(ListView):
    model = Post
    template_name = 'posts/list.html'
    context_object_name = 'posts'
    paginate_by = 10

CreateView

class PostCreate(CreateView):
    model = Post
    fields = ['title', 'body']
    success_url = reverse_lazy('post-list')

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

URLs

2 snippets

URL routing patterns

URL Patterns

from django.urls import path, include

urlpatterns = [
    path('', views.index, name='index'),
    path('posts/<int:pk>/', views.post_detail, name='post-detail'),
    path('posts/<slug:slug>/', views.post_by_slug),
    path('api/', include('api.urls')),
]

Reverse URL

from django.urls import reverse
url = reverse('post-detail', args=[42])
# In template: {% url 'post-detail' post.pk %}

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

QuerySets

4 snippets

Database queries with Django ORM

Filter & Exclude

Post.objects.filter(published=True)
Post.objects.filter(title__icontains='django')
Post.objects.exclude(author=None)
Post.objects.filter(created_at__year=2026)

Q Objects

from django.db.models import Q
Post.objects.filter(
    Q(title__contains='django') | Q(body__contains='django'),
    published=True
)

Annotate & Aggregate

from django.db.models import Count, Avg, F
Post.objects.annotate(comment_count=Count('comments'))
Post.objects.aggregate(avg_score=Avg('score'))
Post.objects.filter(views__gt=F('likes') * 2)

Select Related

# ForeignKey (single query JOIN)
Post.objects.select_related('author')
# ManyToMany (separate query, prefetched)
Post.objects.prefetch_related('tags', 'comments')

Templates

3 snippets

Django template language

Variables & Filters

{{ post.title }}
{{ post.title|truncatewords:30 }}
{{ post.created_at|date:"M d, Y" }}
{{ items|length }}
{{ text|linebreaks }}

Tags

{% if post.published %}
  <h1>{{ post.title }}</h1>
{% endif %}

{% for post in posts %}
  <li>{{ forloop.counter }}. {{ post.title }}</li>
{% empty %}
  <li>No posts yet.</li>
{% endfor %}

Inheritance

{# base.html #}
<html>
<body>{% block content %}{% endblock %}</body>
</html>

{# page.html #}
{% extends "base.html" %}
{% block content %}<h1>Hello</h1>{% endblock %}

Forms

3 snippets

Form handling and validation

ModelForm

from django import forms

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'body']
        widgets = {'body': forms.Textarea(attrs={'rows': 5})}

Validation

class PostForm(forms.ModelForm):
    def clean_title(self):
        title = self.cleaned_data['title']
        if len(title) < 5:
            raise forms.ValidationError('Title too short')
        return title

View Integration

def create_post(request):
    form = PostForm(request.POST or None)
    if form.is_valid():
        post = form.save(commit=False)
        post.author = request.user
        post.save()
        return redirect('post-detail', pk=post.pk)
    return render(request, 'posts/form.html', {'form': form})

More Cheat Sheets

FAQ

Frequently asked questions

What is a Django cheat sheet?

A Django cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in Django. It helps developers quickly look up syntax without searching through documentation.

How do I learn Django quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important Django concepts?

Key Django concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my Django code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your Django code using AI.

Related resources

Stop memorizing. Start shipping.

Generate Django Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week