Django cheatsheet
https://docs.djangoproject.com/en/5.2/
Model fields
- https://docs.djangoproject.com/en/5.2/ref/models/fields/
CharField(max_length=N)
TextField
BooleanField
SlugField
ForeignKey(MODEL, on_delete=models.CASCADE)
IntegerField
DateTimeField
- Set on creation:
auto_now_add=True
- Set on update:
auto_now=True
- Set on creation:
- Create an index:
db_index=True
Template tags
- https://docs.djangoproject.com/en/5.2/ref/templates/builtins/
- Insert raw HTML:
{{ my_html|safe }}
- Pluralize:
{{ n }} thing{{ n|pluralize }}
{{ n }} class{{ n|pluralize:"es" }}
{{ n }} cherr{{ n|pluralize:"y,ies"
- Add commas to numbers:
{% load humanize %} {{ n|intcommas }}
- Requires
django.contrib.humanize
inINSTALLED_APPS
insettings.py
- Requires
- Display date in DMY format:
{{ created_at|date:"j F Y" }}
Get current time
from django.utils import timezone
timezone.now()
Request authentication
request.user.is_authenticated
request.user.is_staff
Handler imports
from django.http import Http404, HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from django.views.decorators.http import require_GET, require_POST
HTTP error
from django.http import HttpResponse
def my_view(request):
# ...
return HttpResponse(status=400)
HTTP redirect
from django.http import HttpResponseRedirect
return HttpResponseRedirect("/path/to/target")
Handle missing model
from django.http import Http404
try:
page_model = Page.objects.get(path=path)
except Page.DoesNotExist:
raise Http404
URLs
from django.urls import include, path
urlpatterns = [
path("blog", views.blog_page),
path("blog/<int:year>/<slug:slug>", views.blog_post_page),
path("myapp", include("myapp.urls")),
]
Management commands
# in <app>/management/commands/
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Create an API key for a user"
def add_argument(self, parser):
# ...
def handle(self, *args, **options):
# ...
Custom admin field name
Use the verbose
parameter for the field in the model class.
Undo migration
You can undo a database migration by migrating to the previous migration:
$ ./manage.py migrate APP 0013