Django Cheat Sheet

Free Django cheat sheet: the most-used Django syntax and methods at a glance — searchable and beginner-friendly.

Project Setup

ConceptSyntaxExample
Start a project
Creates the project skeleton with settings and manage.py.
django-admin startproject namedjango-admin startproject mysite
Create an app
Apps are reusable components; register them in INSTALLED_APPS.
python manage.py startapp namepython manage.py startapp blog
Run dev server
Serves the site locally with auto-reload.
python manage.py runserverpython manage.py runserver 8000
Make migrations
Generates migration files from changes to your models.
python manage.py makemigrationspython manage.py makemigrations blog
Apply migrations
Runs pending migrations against the database.
python manage.py migratepython manage.py migrate
Django shell
An interactive Python shell with Django loaded.
python manage.py shellpython manage.py shell

Models & ORM

ConceptSyntaxExample
Define a model
Each model maps to a database table.
class Post(models.Model):class Post(models.Model): title = models.CharField(max_length=200)
Common fields
auto_now_add stamps the time on creation.
CharField / IntegerField / DateTimeFieldcreated = models.DateTimeField(auto_now_add=True)
Relationships
Also ManyToManyField and OneToOneField for other relations.
ForeignKey(Model, on_delete=...)author = models.ForeignKey(User, on_delete=models.CASCADE)
Query all / filter
.all() returns everything; .filter() narrows by conditions.
Model.objects.filter(...)Post.objects.filter(published=True)
Get one
Raises DoesNotExist if no row matches; use .first() to be safe.
Model.objects.get(pk=id)Post.objects.get(pk=1)
Create & save
Or build an instance and call obj.save().
Model.objects.create(...)Post.objects.create(title="Hi", author=me)

Views & URLs

ConceptSyntaxExample
Function view
Takes a request, returns an HttpResponse.
def view(request): return ...def home(request): return render(request, "home.html")
Render template
Combines a template with a context dict.
render(request, "tpl.html", ctx)return render(request, "post.html", {"post": post})
Class-based view
Generic views handle common list/detail/CRUD patterns.
class V(ListView):class PostList(ListView): model = Post
URL pattern
Define routes in urls.py; <int:pk> captures a typed param.
path("route/", view, name=...)path("posts/<int:pk>/", detail, name="detail")
Include app URLs
Delegates a URL prefix to an app's own urlconf.
include("app.urls")path("blog/", include("blog.urls"))
Reverse a URL
Build a URL from its name instead of hardcoding it.
reverse("name", args=[...])reverse("detail", args=[post.pk])

Templates

ConceptSyntaxExample
Output a variable
Double braces print a context value, auto-escaped.
{{ variable }}<h1>{{ post.title }}</h1>
Conditionals
Logic blocks use {% %} tags and must be closed.
{% if cond %} ... {% endif %}{% if user.is_authenticated %}Hi{% endif %}
Loops
Iterate over a queryset or list from the context.
{% for x in list %} ... {% endfor %}{% for p in posts %}{{ p.title }}{% endfor %}
Template inheritance
Reuse a layout and override named blocks.
{% extends "base.html" %}{% extends "base.html" %} {% block content %}...{% endblock %}
URL tag
Build links by view name inside templates.
{% url "name" arg %}<a href="{% url 'detail' post.pk %}">Read</a>
Filters
Transform output, e.g. date, length, default, upper.
{{ value|filter }}{{ post.created|date:"Y-m-d" }}

Forms

ConceptSyntaxExample
Define a form
Declarative fields with built-in validation.
class F(forms.Form):class ContactForm(forms.Form): email = forms.EmailField()
Model form
Builds a form straight from a model's fields.
class F(forms.ModelForm):class PostForm(forms.ModelForm): class Meta: model = Post fields = ["title"]
Handle submission
Bind POST data, validate, then save or read cleaned_data.
if form.is_valid():form = PostForm(request.POST) if form.is_valid(): form.save()
Cleaned data
Validated, type-converted values after is_valid().
form.cleaned_data["field"]email = form.cleaned_data["email"]
Render in template
as_p, as_table or as_ul render all fields quickly.
{{ form.as_p }}<form method="post">{% csrf_token %}{{ form.as_p }}</form>
CSRF token
Required in every POST form to pass CSRF protection.
{% csrf_token %}<form method="post">{% csrf_token %}...</form>

Admin & Auth

ConceptSyntaxExample
Register a model
Makes the model editable in the admin site.
admin.site.register(Model)from .models import Post admin.site.register(Post)
Customize admin
Control list columns, filters and search in the admin.
class A(admin.ModelAdmin):@admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ["title"]
Create superuser
Makes an account that can log into /admin/.
python manage.py createsuperuserpython manage.py createsuperuser
Login required
Redirects anonymous users to the login page.
@login_requiredfrom django.contrib.auth.decorators import login_required @login_required def dash(request): ...
Current user
The logged-in User, or AnonymousUser if not signed in.
request.userif request.user.is_authenticated: ...
Authenticate & login
Check credentials, then start a session.
authenticate() / login()user = authenticate(username=u, password=p) if user: login(request, user)