Django Exercises
Time to practise! Each exercise has a starter playground that already contains the Django setup and runs as-is, printing a placeholder result. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. If you get stuck, open the solution — but give it a real try first.
| # | Exercise | Topics |
|---|---|---|
| 1 | Hello view with a URL parameter | views, URLs, test client |
| 2 | Template loop with a filter | templates, for, filters |
| 3 | Create and query a model | models, create, filter, order_by |
| 4 | Bulk price update | update(), F expressions |
| 5 | Posts per author | ForeignKey, annotate, Count |
| 6 | Validate a form | forms, clean_<field> |
| 7 | JSON detail endpoint | JsonResponse, get_object_or_404 |
| 8 | Visit counter in the session | sessions, middleware |
1. Hello view with a URL parameter
Write a view hello(request, name) mapped to hello/<str:name>/ that responds with Hello, <Name>! where the name is capitalised. A query parameter ?shout=1 should make the whole greeting upper-case.
Expected:
Hello, Minh!
HELLO, MINH!import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"])
django.setup()
from django.http import HttpResponse
from django.urls import path
from django.test import Client
def hello(request, name):
return HttpResponse("TODO") # TODO: build the greeting
urls.urlpatterns = [path("hello/<str:name>/", hello)]
c = Client()
print(c.get("/hello/minh/").content.decode())
print(c.get("/hello/minh/?shout=1").content.decode())TODO
TODO
Show solution
def hello(request, name):
text = f"Hello, {name.capitalize()}!"
if request.GET.get("shout") == "1":
text = text.upper()
return HttpResponse(text)2. Template loop with a filter
Complete the template so it prints a numbered list of the dishes, with each name in title case and the price with two decimals, and Menu is empty when there are no dishes.
Expected:
1. Pho Bo - 5.50
2. Banh Xeo - 4.00
3. Che Ba Mau - 2.25
Menu is emptyimport django
from django.conf import settings
settings.configure(TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}])
django.setup()
from django.template import Template, Context
menu = Template("TODO: loop over dishes") # TODO: write the template
dishes = [{"name": "pho bo", "price": 5.5}, {"name": "banh xeo", "price": 4},
{"name": "che ba mau", "price": 2.25}]
print(menu.render(Context({"dishes": dishes})))
print(menu.render(Context({"dishes": []})))TODO: loop over dishes
TODO: loop over dishes
Show solution
menu = Template(
"{% for d in dishes %}{{ forloop.counter }}. {{ d.name|title }} - {{ d.price|floatformat:2 }}"
"{% if not forloop.last %}\n{% endif %}"
"{% empty %}Menu is empty{% endfor %}"
)3. Create and query a model
Define a Movie model with title (text), year (integer) and rating (integer 1–10). Insert the four movies below, then print the titles of movies from 2000 or later with a rating of at least 8, sorted by rating descending (ties by title).
Expected: ['Parasite', 'Spirited Away', 'Inception']
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
class Movie(models.Model):
title = models.CharField(max_length=100)
# TODO: add year and rating
class Meta:
app_label = "demo"
with connection.schema_editor() as editor:
editor.create_model(Movie)
data = [("Inception", 2010, 8), ("Spirited Away", 2001, 9), ("Parasite", 2019, 9), ("Alien", 1979, 8)]
for title, year, rating in data:
Movie.objects.create(title=title) # TODO: also store year and rating
result = Movie.objects.all() # TODO: filter and order
print([m.title for m in result])['Inception', 'Spirited Away', 'Parasite', 'Alien']
Show solution
class Movie(models.Model):
title = models.CharField(max_length=100)
year = models.IntegerField()
rating = models.IntegerField()
class Meta:
app_label = "demo"
# ... create the table ...
for title, year, rating in data:
Movie.objects.create(title=title, year=year, rating=rating)
result = Movie.objects.filter(year__gte=2000, rating__gte=8).order_by("-rating", "title")
print([m.title for m in result])4. Bulk price update
A shop raises the price of every product in the "tea" category by 2 (in one query, using F), and marks products with stock=0 as inactive. Print how many rows each update changed, then the products.
Expected:
raised: 2
deactivated: 1
Green tea 6 True
Oolong 9 False
Mug 8 Trueimport django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
from django.db.models import F
class Product(models.Model):
name = models.CharField(max_length=30)
category = models.CharField(max_length=20)
price = models.IntegerField()
stock = models.IntegerField()
active = models.BooleanField(default=True)
class Meta:
app_label = "demo"
with connection.schema_editor() as editor:
editor.create_model(Product)
Product.objects.create(name="Green tea", category="tea", price=4, stock=10)
Product.objects.create(name="Oolong", category="tea", price=7, stock=0)
Product.objects.create(name="Mug", category="gear", price=8, stock=3)
raised = 0 # TODO: one update() with F("price") + 2
deactivated = 0 # TODO: one update() for stock=0
print("raised:", raised)
print("deactivated:", deactivated)
for p in Product.objects.order_by("id"):
print(p.name, p.price, p.active)raised: 0
deactivated: 0
Green tea 4 True
Oolong 7 True
Mug 8 True
Show solution
raised = Product.objects.filter(category="tea").update(price=F("price") + 2)
deactivated = Product.objects.filter(stock=0).update(active=False)5. Posts per author
Using the Author and Post models below, print each author with their number of published posts, most first (ties by name). Authors with no published posts must appear with 0. Use a single query with annotate().
Expected:
Hanh 2
Quang 1
Vy 0import sys, types, django
from django.conf import settings
sys.modules["demo"] = types.ModuleType("demo")
sys.modules["demo"].__file__ = "demo/__init__.py"
settings.configure(INSTALLED_APPS=["demo"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
from django.db.models import Count, Q
class Author(models.Model):
name = models.CharField(max_length=30)
class Meta:
app_label = "demo"
class Post(models.Model):
title = models.CharField(max_length=50)
published = models.BooleanField(default=False)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="posts")
class Meta:
app_label = "demo"
with connection.schema_editor() as editor:
editor.create_model(Author)
editor.create_model(Post)
hanh, quang, vy = (Author.objects.create(name=n) for n in ["Hanh", "Quang", "Vy"])
for title, pub, a in [("A", True, hanh), ("B", True, hanh), ("C", False, hanh),
("D", True, quang), ("E", False, vy)]:
Post.objects.create(title=title, published=pub, author=a)
authors = Author.objects.order_by("name") # TODO: annotate and order
for a in authors:
print(a.name, "?") # TODO: print the countHanh ?
Quang ?
Vy ?
Show solution
authors = (Author.objects
.annotate(n=Count("posts", filter=Q(posts__published=True)))
.order_by("-n", "name"))
for a in authors:
print(a.name, a.n)6. Validate a form
Finish RegisterForm: username must be 3–15 characters and is stored in lower case; password and confirm must match (a non-field error Passwords do not match.).
Expected:
True {'username': 'linh', 'password': 'pa55word', 'confirm': 'pa55word'}
False ['Ensure this value has at least 3 characters (it has 2).'] ['Passwords do not match.']import django
from django.conf import settings
settings.configure()
django.setup()
from django import forms
class RegisterForm(forms.Form):
username = forms.CharField() # TODO: length limits
password = forms.CharField()
confirm = forms.CharField()
# TODO: clean_username() and clean()
good = RegisterForm({"username": "LINH", "password": "pa55word", "confirm": "pa55word"})
print(good.is_valid(), good.cleaned_data)
bad = RegisterForm({"username": "Al", "password": "a", "confirm": "b"})
print(bad.is_valid(), list(bad.errors.get("username", [])), list(bad.non_field_errors()))True {'username': 'LINH', 'password': 'pa55word', 'confirm': 'pa55word'}
True [] []
Show solution
class RegisterForm(forms.Form):
username = forms.CharField(min_length=3, max_length=15)
password = forms.CharField()
confirm = forms.CharField()
def clean_username(self):
return self.cleaned_data["username"].lower()
def clean(self):
cleaned = super().clean()
if cleaned.get("password") != cleaned.get("confirm"):
raise forms.ValidationError("Passwords do not match.")
return cleaned7. JSON detail endpoint
Write city_detail(request, pk) that returns the city as JSON (id, name, population) and a 404 for unknown ids. Use get_object_or_404.
Expected:
200 {'id': 2, 'name': 'Da Nang', 'population': 1220000}
404import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.urls import path
from django.test import Client
class City(models.Model):
name = models.CharField(max_length=50)
population = models.IntegerField()
class Meta:
app_label = "demo"
with connection.schema_editor() as editor:
editor.create_model(City)
City.objects.create(name="Hue", population=650000)
City.objects.create(name="Da Nang", population=1220000)
def city_detail(request, pk):
return JsonResponse({"todo": True}) # TODO
urls.urlpatterns = [path("api/cities/<int:pk>/", city_detail)]
c = Client()
r = c.get("/api/cities/2/")
print(r.status_code, r.json())
print(c.get("/api/cities/9/").status_code)200 {'todo': True}
200
Show solution
def city_detail(request, pk):
city = get_object_or_404(City, pk=pk)
return JsonResponse({"id": city.pk, "name": city.name, "population": city.population})8. Visit counter in the session
Make / count the visits per visitor using request.session, answering Visit #N. Two separate clients must have separate counters. The setup already uses the signed-cookie session engine and SessionMiddleware.
Expected:
Visit #1
Visit #2
Visit #3
Visit #1import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo-secret", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
SESSION_ENGINE="django.contrib.sessions.backends.signed_cookies",
MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"])
django.setup()
from django.http import HttpResponse
from django.urls import path
from django.test import Client
def home(request):
count = 1 # TODO: read, increment and store in the session
return HttpResponse(f"Visit #{count}")
urls.urlpatterns = [path("", home)]
first, second = Client(), Client()
for _ in range(3):
print(first.get("/").content.decode())
print(second.get("/").content.decode())Visit #1
Visit #1
Visit #1
Visit #1
Show solution
def home(request):
count = request.session.get("count", 0) + 1
request.session["count"] = count
return HttpResponse(f"Visit #{count}")Test yourself
Which call changes many rows in one query and returns the number changed?
- save()
- QuerySet.update()
- bulk_create()
- get_or_create()
In exercise 5, why does an author with no published posts still appear with 0?
- Django adds missing rows by default
- annotate(Count(...)) uses a LEFT OUTER JOIN
- Because of order_by
- It doesn't appear