Quick Reference Django Cheatsheet
Django 5 on one page — the project layout, settings and URLs, models, the ORM, function
views, templates, forms, the admin, tests, and the traps that show up in interviews.
10 sections 10 tables 17 code snippets Create and run django-admin startproject shop
python manage.py startapp books
python manage.py makemigrations
python manage.py migrate
python manage.py runserver What each command does startproject settings, urls, wsgi
startapp models, views, admin
makemigrations writes a migration file
migrate applies it to the database
runserver http://127.0.0.1:8000 This page is Django 5. A new app does nothing until its dotted path is in INSTALLED_APPS. Production settings worth setting SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
DEBUG = False
ALLOWED_HOSTS = ["shop.example.com"] A named route urlpatterns = [
path("books/", views.book_list, name="book-list"),
path("books/<int:pk>/", views.book_detail, name="book-detail"),
] A table class Book(models.Model):
title = models.CharField(max_length=200)
pages = models.PositiveIntegerField()
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["-created"]
def __str__(self):
return self.title Editing a model does not change the database. Run makemigrations, read the file, then migrate. Commit the migration. Read and write Book.objects.create(title="Django", pages=300)
Book.objects.filter(pages__gte=100)
Book.objects.get(pk=pk) Follow a relation books = Book.objects.prefetch_related("reviews")
for book in books:
for review in book.reviews.all():
print(review.rating) A queryset is lazy. It hits the database when you loop, slice, or call len. Build it fully, then evaluate it once. List def book_list(request):
books = Book.objects.all()
return render(request, "books/list.html", {"books": books}) Create @login_required
def book_create(request):
form = BookForm(request.POST or None)
if form.is_valid():
form.save()
return redirect("book-list")
return render(request, "books/form.html", {"form": form}) request.POST or None keeps a GET form unbound. An unbound form does not show “this field is required” before the user has typed anything. A list page {% extends "base.html" %}
{% block content %}
<ul>
{% for book in books %}
<li>{{ book.title }}</li>
{% empty %}
<li>No books yet</li>
{% endfor %}
</ul>
{% endblock %} |safe marks a string as HTML. Use it only for markup you wrote. A book title belongs in {{ book.title }}, which escapes it. Register a model @admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ["title", "pages"]
search_fields = ["title"] A superuser python manage.py createsuperuser
Passwords are hashed. Read request.user and the auth helpers. Do not store a password column of your own. A view test class BookViewTests(TestCase):
def test_list_is_empty(self):
response = self.client.get("/books/")
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No books yet") Create rows with the ORM inside the test. TestCase is not looking at your development database. One query for the children books = Book.objects.prefetch_related("reviews") A missing book is a 404 book = get_object_or_404(Book, pk=pk) How to use this page: start a project, add books to INSTALLED_APPS, and make one model. Migrate, register it in the admin, then add a list view whose template uses {% csrf_token %} on the create form. |