Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 77 ยท Practice and Review

Django Exercises with Solutions

18 graded Django exercises with runnable solutions: queries, aggregation, transactions, views, URLs, forms, authentication, middleware and tests.

Reading about Django and writing Django are different skills. This page gives you 18 exercises that cover the core of the framework: the ORM, transactions and constraints, views and URLs, forms, authentication, middleware and tests. They are ordered from beginner to advanced inside each group, and every one runs in your browser.

Each exercise has a short task, an editor with the setup already written, and a hidden solution. The setup (settings, models, sample data) sits above the line # --- your code below ---. Write your answer below that line, press Run, and compare your output with the comments in the editor. Then open the solution and compare approaches.

Here is how to get the most out of them:

  • Try first, peek later. Give each exercise an honest attempt before opening the solution. Being stuck for a few minutes is where the learning happens.
  • Check the output, not only the code. Each editor lists the expected output in a comment. Your code can look different and still be right.
  • Read the SQL when in doubt. print(queryset.query) shows the SQL Django will run for a queryset.
  • Keep the references nearby. The cheat sheet lists lookups, template tags and assertions, and the common mistakes page explains the traps that these exercises hint at.

All ORM exercises share one small data set: four authors and eight books. The author Omar Haddad has no books on purpose, because empty relations are where many queries go wrong.

erDiagram
    AUTHOR ||--o{ BOOK : writes
    AUTHOR {
        int id
        string name
    }
    BOOK {
        int id
        string title
        int author_id
        int year
        int pages
        decimal price
    }

The Author and Book models used by the ORM, form and view exercises.

Queries and the ORM

These practice CRUD with QuerySets, lookups and Q objects, relationships, aggregation and ORM performance.

Create the author Zed Quinn and give them two books through the reverse manager (zed.books.create(...)). Then print how many books Zed has and how many books exist in total.

Python Exercise 1: Create related rows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
zed = Author.objects.create(name="Zed Quinn")
zed.books.create(title="Zero Day", year=2023, pages=300, price=Decimal("19.00"))
zed.books.create(title="Cold Start", year=2024, pages=250, price=Decimal("17.50"))

print(zed.books.count())
print(Book.objects.count())

The reverse manager fills in the foreign key for you, so you never pass author=zed. count() runs SELECT COUNT(*) in the database instead of loading rows.

2. Filter and order (Beginner)

Print every book published in 2000 or later that costs less than 25, newest first, as Title (year) $price.

Python Exercise 2: Filter and order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
recent = Book.objects.filter(year__gte=2000, price__lt=25).order_by("-year")
for book in recent:
    print(f"{book.title} ({book.year}) ${book.price}")

Keyword arguments in one filter() call are combined with AND. A leading minus in order_by means descending.

3. Combine conditions with Q (Beginner)

Find books whose title contains "the" (ignoring case) or that have at least 500 pages, but exclude everything by Mira Stone. Print the titles in alphabetical order.

Python Exercise 3: Q objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
from django.db.models import Q

books = (
    Book.objects.filter(Q(title__icontains="the") | Q(pages__gte=500))
    .exclude(author__name="Mira Stone")
    .order_by("title")
)
for book in books:
    print(book.title)

| between Q objects means OR, & means AND and ~ means NOT. The double underscore in author__name follows the foreign key into the Author table.

4. Update many rows with F (Intermediate)

Give every book published before 2000 a 20% discount in one query (no loop, no save()), and print how many rows changed. Then list the discounted titles with their new prices.

Python Exercise 4: F expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
from django.db.models import F

changed = Book.objects.filter(year__lt=2000).update(price=F("price") * Decimal("0.80"))
print("changed:", changed)

for book in Book.objects.filter(year__lt=2000):
    print(book.title, book.price)

F("price") refers to the column, so the database multiplies each row's own value. The same idea makes counters safe, as in the polls project.

5. Group and aggregate (Intermediate)

For each author print the number of books and the average page count (rounded to a whole number, or - when there are no books), ordered by book count descending and then by name. Finally print the total price of all books with aggregate.

Python Exercise 5: Aggregation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
from django.db.models import Avg, Count, Sum

stats = Author.objects.annotate(
    n=Count("books"), avg_pages=Avg("books__pages")
).order_by("-n", "name")

for author in stats:
    avg = round(author.avg_pages) if author.avg_pages is not None else "-"
    print(f"{author.name}: {author.n} books, average pages {avg}")

total = Book.objects.aggregate(total=Sum("price"))["total"]
print("Total price:", total.quantize(Decimal("0.01")))

annotate adds a value to each row (one per author), while aggregate collapses everything into one dictionary. Because authors are joined with their books using a LEFT JOIN, Omar Haddad still appears with a count of 0. SQLite sums decimals as floating-point numbers, so the sum is quantized to two places before printing; other databases return an exact Decimal.

6. Fix an N+1 problem (Intermediate)

Build the list "Title by Author" for all books and count the queries with CaptureQueriesContext. First do it the naive way, then fix it with select_related. Finally loop over authors and their book titles with prefetch_related and count again.

Python Exercise 6: N+1 queries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
with CaptureQueriesContext(connection) as naive:
    lines = [f"{b.title} by {b.author.name}" for b in Book.objects.all()]
print("naive:", len(naive))

with CaptureQueriesContext(connection) as joined:
    lines = [f"{b.title} by {b.author.name}" for b in Book.objects.select_related("author")]
print("select_related:", len(joined))

with CaptureQueriesContext(connection) as prefetched:
    for author in Author.objects.prefetch_related("books"):
        titles = [b.title for b in author.books.all()]
print("prefetch_related:", len(prefetched))

The naive loop runs one query for the books plus one per book to fetch its author: 1 + 8 = 9. select_related follows a forward foreign key with a JOIN (1 query). prefetch_related runs a second query for all related books and stitches them together in Python (2 queries); it is the tool for reverse and many-to-many relations.

7. Missing and repeated relations (Intermediate)

Print (a) the names of authors who have no books, (b) the names of authors with at least three books and (c) the names of authors who published a book in 2020 or later, without duplicates.

Python Exercise 7: Relations in filters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
from django.db.models import Count

print([a.name for a in Author.objects.filter(books__isnull=True)])

prolific = Author.objects.annotate(n=Count("books")).filter(n__gte=3).order_by("name")
print([a.name for a in prolific])

print(list(Author.objects.filter(books__year__gte=2020).distinct().values_list("name", flat=True)))

Filtering across a one-to-many relation can return the same author once per matching book, so distinct() removes the repeats. Filtering on an annotation (n__gte=3) becomes a HAVING clause. Queries that group rows ignore Meta.ordering, so the explicit order_by("name") is needed for a stable order.

8. Buckets with Case and When (Advanced)

Label each book cheap (under 15), mid (under 25) or premium, then print how many books fall into each label, sorted by label.

Python Exercise 8: Conditional annotations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
from django.db.models import Case, Count, Value, When

labeled = Book.objects.annotate(
    tier=Case(
        When(price__lt=15, then=Value("cheap")),
        When(price__lt=25, then=Value("mid")),
        default=Value("premium"),
    )
)
for row in labeled.values("tier").annotate(n=Count("id")).order_by("tier"):
    print(row["tier"], row["n"])

Case works like if/elif/else inside SQL, and the first matching When wins. Calling values("tier") before annotate(n=...) groups the rows by label.

Transactions and constraints

These practice transactions, models and custom managers and constraints.

9. All or nothing (Intermediate)

Write transfer(source, target, amount) that moves money between two Account rows inside transaction.atomic(). Use F() for the updates, and raise ValueError("insufficient funds") when the source balance would go negative. Show that a failed transfer leaves both balances untouched.

Python Exercise 9: Atomic transfer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
from django.db import transaction
from django.db.models import F


def transfer(source, target, amount):
    with transaction.atomic():
        Account.objects.filter(owner=source).update(balance=F("balance") - amount)
        Account.objects.filter(owner=target).update(balance=F("balance") + amount)
        if Account.objects.get(owner=source).balance < 0:
            raise ValueError("insufficient funds")


transfer("Ada", "Bo", 30)

try:
    transfer("Ada", "Bo", 500)
except ValueError as error:
    print("failed:", error)

print({a.owner: a.balance for a in Account.objects.order_by("owner")})

When the exception leaves the atomic() block, Django rolls back both updates, so the failed transfer changed nothing. On a database that supports row locks (PostgreSQL, MySQL) you would also use select_for_update() to lock the rows while checking.

10. Let the database enforce a rule (Intermediate)

Define a Product model whose stock can never be negative, using a CheckConstraint. Create a valid product, then try to create one with stock=-1 and catch the IntegrityError. Finally, call full_clean() on an invalid instance and print which error key Django reports.

Python Exercise 10: CheckConstraint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
class Product(models.Model):
    name = models.CharField(max_length=40)
    stock = models.IntegerField()

    class Meta:
        app_label = "shop"
        constraints = [
            models.CheckConstraint(condition=models.Q(stock__gte=0), name="stock_not_negative"),
        ]


with connection.schema_editor() as editor:
    editor.create_model(Product)

Product.objects.create(name="Lamp", stock=5)

try:
    Product.objects.create(name="Ghost", stock=-1)
except IntegrityError:
    print("database rejected stock=-1")

try:
    Product(name="Ghost", stock=-1).full_clean()
except ValidationError as error:
    print(list(error.message_dict))

print(Product.objects.count())

The constraint lives in the database, so it protects against every code path, including raw SQL and other programs. full_clean() also checks constraints in Python and reports them under the __all__ key, which lets forms show a friendly error before any SQL runs. (Older Django versions spell the argument check= instead of condition=.)

Views and URLs

These practice URL routing, function-based views and generic views.

11. A JSON endpoint (Intermediate)

Write a view book_list for /api/books/ that returns {"count": n, "results": [...]} with each book's title, author name and year, ordered by year. Support an optional ?min_year= filter, and answer 400 with an error message when it is not a number. Call it with the test Client.

Python Exercise 11: JSON endpoint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
def book_list(request):
    books = Book.objects.select_related("author").order_by("year")
    min_year = request.GET.get("min_year")
    if min_year is not None:
        if not min_year.isdigit():
            return JsonResponse({"error": "min_year must be a number"}, status=400)
        books = books.filter(year__gte=int(min_year))
    data = [{"title": b.title, "author": b.author.name, "year": b.year} for b in books]
    return JsonResponse({"count": len(data), "results": data})


project.urlpatterns = [path("api/books/", book_list)]

client = Client()
response = client.get("/api/books/", {"min_year": 2016})
print(response.status_code, response.json())

response = client.get("/api/books/", {"min_year": "abc"})
print(response.status_code, response.json())

Validate query-string input before using it: request.GET values are always strings. select_related("author") keeps the view at one query no matter how many books match.

12. Named URLs, converters and namespaces (Beginner)

Build a URL configuration with two patterns under /books/: <int:pk>/ named detail and by/<slug:slug>/ named by-author, both in the namespace catalog. Print the result of reverse() for each, then resolve /books/42/ and show the view name and arguments. Show that /books/abc/ does not match.

Python Exercise 12: Reverse and resolve

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
from django.urls import Resolver404, include, path, resolve, reverse

book_patterns = [
    path("<int:pk>/", book_detail, name="detail"),
    path("by/<slug:slug>/", author_books, name="by-author"),
]
urls = types.ModuleType("urls")
urls.urlpatterns = [path("books/", include((book_patterns, "catalog")))]

print(reverse("catalog:detail", args=[7], urlconf=urls))
print(reverse("catalog:by-author", kwargs={"slug": "mira-stone"}, urlconf=urls))

match = resolve("/books/42/", urlconf=urls)
print(match.view_name, match.kwargs)

try:
    resolve("/books/abc/", urlconf=urls)
except Resolver404:
    print("no match")

In a real project the module is your urls.py and you would omit urlconf=. The int converter only matches digits and passes an int to the view, which is why abc never reaches book_detail. Always build links with reverse() or {% url %} so a renamed path cannot break them.

13. A paginated ListView (Intermediate)

Create a ListView of books ordered by title with three books per page, using the template name book_list.html (already provided in memory). Print page 1, then page 3, and show that page 4 returns status 404.

Python Exercise 13: ListView

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
class BookListView(ListView):
    queryset = Book.objects.order_by("title")
    template_name = "book_list.html"
    paginate_by = 3


project.urlpatterns = [path("books/", BookListView.as_view())]

client = Client()
print(client.get("/books/").content.decode())
print(client.get("/books/?page=3").content.decode())
print(client.get("/books/?page=4").status_code)

paginate_by adds page_obj, paginator and is_paginated to the context, and an out-of-range page raises a 404 for you. A queryset attribute is evaluated once per request, so it is safe to define at class level.

Forms

These practice Django forms, validation and ModelForms.

14. Validate a signup form (Intermediate)

Build a SignupForm with username (3-20 characters), age (13 or older), password (at least 8 characters) and password2. Reject the usernames admin and root in clean_username, store the username in lowercase, and attach a "Passwords do not match." error to password2 in clean(). Print the result of a good submission and every error of a bad one.

Python Exercise 14: Form validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
class SignupForm(forms.Form):
    username = forms.CharField(min_length=3, max_length=20)
    age = forms.IntegerField(min_value=13)
    password = forms.CharField(min_length=8)
    password2 = forms.CharField()

    def clean_username(self):
        username = self.cleaned_data["username"].strip().lower()
        if username in {"admin", "root"}:
            raise forms.ValidationError("That username is reserved.", code="reserved")
        return username

    def clean(self):
        cleaned = super().clean()
        if cleaned.get("password") and cleaned.get("password") != cleaned.get("password2"):
            self.add_error("password2", "Passwords do not match.")
        return cleaned


good = SignupForm({"username": "  Mira ", "age": "30", "password": "longenough", "password2": "longenough"})
print(good.is_valid(), good.cleaned_data["username"])

bad = SignupForm({"username": "Admin", "age": "9", "password": "longenough", "password2": "different"})
print(bad.is_valid())
for field, errors in bad.errors.items():
    print(field, list(errors))

clean_<field>() validates and normalizes one field; clean() sees all fields and is the place for rules that compare them. CharField strips surrounding whitespace by default. Use add_error in clean() to attach a problem to a specific field instead of the whole form.

15. Save through a ModelForm (Intermediate)

Create a BookForm (a ModelForm for Book with title, author, year, pages and price) that also rejects prices of zero or less. Save a valid submission and print its id, title and author. Then submit an invalid form (empty title, a year of "x", price -1) and print the sorted names of the fields with errors.

Python Exercise 15: ModelForm

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ["title", "author", "year", "pages", "price"]

    def clean_price(self):
        price = self.cleaned_data["price"]
        if price <= 0:
            raise forms.ValidationError("Price must be positive.")
        return price


form = BookForm({"title": "Dust", "author": mira.pk, "year": 2024, "pages": 200, "price": "15.00"})
print(form.is_valid())
book = form.save()
print(book.pk, book.title, book.author)

bad = BookForm({"title": "", "author": mira.pk, "year": "x", "pages": 10, "price": "-1"})
print(sorted(bad.errors))

A ModelForm builds its fields from the model, applies the model's validators and writes the instance with save(). Always list fields explicitly in Meta.fields so a new model column never becomes editable by accident.

Authentication, middleware and tests

These practice authentication, middleware and testing.

16. Protect a view (Intermediate)

Create the user mira, verify authenticate() with a right and a wrong password, and write a login_required view at /secret/ that answers hello <username>. Show the redirect an anonymous visitor gets, then log in with the test client and request the page again.

Python Exercise 16: login_required

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.test import Client
from django.urls import path

User.objects.create_user("mira", password="s3cret-pass")
print(authenticate(username="mira", password="s3cret-pass") is not None)
print(authenticate(username="mira", password="wrong"))


@login_required
def secret(request):
    return HttpResponse(f"hello {request.user.username}")


project.urlpatterns = [path("secret/", secret)]

client = Client()
response = client.get("/secret/")
print(response.status_code, response["Location"])

print(client.login(username="mira", password="s3cret-pass"))
response = client.get("/secret/")
print(response.status_code, response.content.decode())

authenticate() returns the user or None. An anonymous request to a login_required view is redirected to LOGIN_URL with the original path in ?next=. The test client's login() creates a session without going through the form.

17. Write a middleware (Intermediate)

The project already lists mw.length_middleware in MIDDLEWARE. Write that function so that every response gets an X-Body-Length header containing the length of the response body, assign it to mw.length_middleware, and request /hello/.

Python Exercise 17: Middleware

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
def length_middleware(get_response):
    def middleware(request):
        response = get_response(request)
        response["X-Body-Length"] = str(len(response.content))
        return response

    return middleware


mw.length_middleware = length_middleware

client = Client()
response = client.get("/hello/")
print(response.status_code, response["X-Body-Length"])

A function middleware is a factory: Django calls it once with get_response, and the inner function runs for every request. Code before get_response(request) runs on the way in, and code after it runs on the way out. Header values must be strings.

18. Test a view (Advanced)

The greet view answers Hello, <name>! for GET /greet/?name=... and rejects other methods. Write a SimpleTestCase with four tests: the default name, a custom name, HTML in the name is escaped and a POST gets status 405. Run it programmatically and print the number of tests, failures and errors.

Python Exercise 18: Test case

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
class GreetTests(SimpleTestCase):
    def test_default_name(self):
        self.assertContains(self.client.get("/greet/"), "Hello, stranger!")

    def test_custom_name(self):
        self.assertContains(self.client.get("/greet/", {"name": "Mira"}), "Hello, Mira!")

    def test_name_is_escaped(self):
        response = self.client.get("/greet/", {"name": "<b>"})
        self.assertNotContains(response, "<b>")

    def test_post_is_not_allowed(self):
        self.assertEqual(self.client.post("/greet/").status_code, 405)


result = unittest.TestResult()
unittest.defaultTestLoader.loadTestsFromTestCase(GreetTests).run(result)
print(result.testsRun, len(result.failures), len(result.errors))

SimpleTestCase is the right base class when a test needs no database. To watch a test fail, change escape(name) in the view to name and run again: the escaping test turns red while the others stay green.

Where to go next

If an exercise felt hard, go back to its lesson and redo the live examples before trying again. If they all felt easy, build one of the projects, then test yourself with the interview questions. A good habit is to redo an exercise a week later without looking at the solution.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In exercise 6, why does the naive loop run 9 queries for 8 books?

    Accessing book.author on an unloaded foreign key triggers a new query for every book. select_related loads the authors in the same JOIN.
  2. 2. Which tool makes a failed transfer undo every update it already made?

    An exception that leaves an atomic block rolls the transaction back, so none of the writes inside it are kept.
  3. 3. What is the difference between annotate() and aggregate()?

    annotate() keeps one result per object (or per group), while aggregate() collapses the queryset into a single dictionary.
  4. 4. Where should a rule that compares two form fields, such as matching passwords, be validated?

    clean() runs after all fields have been cleaned, so it can compare their values and attach errors with add_error().

Summary

  • Practice by writing first and reading the solution second; compare your output with the expected output.
  • Use Q, F, Case/When, annotate and aggregate to let the database do filtering, arithmetic and grouping.
  • Count queries with CaptureQueriesContext, and fix N+1 problems with select_related (forward relations) and prefetch_related (reverse and many-to-many).
  • Wrap multi-step writes in transaction.atomic() and enforce invariants with database constraints.
  • Validate input in forms (clean_<field>, clean), and keep views thin and testable with the test Client.
  • Protect views with login_required, add cross-cutting behavior with middleware and prove it with tests.

Next lesson: Common Django Mistakes.