Django Cheat Sheet
Free Django cheat sheet: the most-used Django syntax and methods at a glance — searchable and beginner-friendly.
Project Setup
| Concept | Syntax | Example |
|---|---|---|
| Start a project Creates the project skeleton with settings and manage.py. | django-admin startproject name | django-admin startproject mysite |
| Create an app Apps are reusable components; register them in INSTALLED_APPS. | python manage.py startapp name | python manage.py startapp blog |
| Run dev server Serves the site locally with auto-reload. | python manage.py runserver | python manage.py runserver 8000 |
| Make migrations Generates migration files from changes to your models. | python manage.py makemigrations | python manage.py makemigrations blog |
| Apply migrations Runs pending migrations against the database. | python manage.py migrate | python manage.py migrate |
| Django shell An interactive Python shell with Django loaded. | python manage.py shell | python manage.py shell |
Models & ORM
| Concept | Syntax | Example |
|---|---|---|
| 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 / DateTimeField | created = 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
| Concept | Syntax | Example |
|---|---|---|
| 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
| Concept | Syntax | Example |
|---|---|---|
| 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
| Concept | Syntax | Example |
|---|---|---|
| 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
| Concept | Syntax | Example |
|---|---|---|
| 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 createsuperuser | python manage.py createsuperuser |
| Login required Redirects anonymous users to the login page. | @login_required | from 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.user | if 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) |