True mastery in web development comes from solving real-world engineering challenges. Below are 15 progressive hands-on coding labs designed to cement your understanding of Django's ORM, views, forms, authentication, REST APIs, and background processing.
Challenges 1 – 5 (MVT, ORM, Forms)
Challenges 6 – 10 (Auth, CBVs, Custom Managers)
Challenges 11 – 15 (DRF, Celery, N+1, Middleware)
Problem: Create models for Author, Category, and Post. Ensure every post has an auto-generated unique slug, an author foreign key with cascade deletion, a category with set-null deletion, and a ManyToMany relationship with Tag.
# Solution to Lab 1:
from django.db import models
from django.utils.text import slugify
class Category(models.Model):
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(unique=True, blank=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
super().save(*args, **kwargs)
class Tag(models.Model):
name = models.CharField(max_length=50, unique=True)
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True, blank=True)
author = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='posts')
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='posts')
tags = models.ManyToManyField(Tag, blank=True, related_name='posts')
created_at = models.DateTimeField(auto_now_add=True)
Problem: Create a ProductQuerySet that defines chainable methods: in_stock() (stock > 0), discounted() (discount_price < price), and top_rated() (average_rating >= 4.5).
# Solution to Lab 6:
from django.db import models
from django.db.models import F
class ProductQuerySet(models.QuerySet):
def in_stock(self):
return self.filter(stock_quantity__gt=0)
def discounted(self):
return self.filter(discount_price__lt=F('price'), discount_price__isnull=False)
def top_rated(self):
return self.filter(average_rating__gte=4.5)
class Product(models.Model):
name = models.CharField(max_length=150)
price = models.DecimalField(max_digits=8, decimal_places=2)
discount_price = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True)
stock_quantity = models.PositiveIntegerField(default=0)
average_rating = models.FloatField(default=0.0)
objects = ProductQuerySet.as_manager()
Problem: You are tasked with optimizing an API endpoint that lists 50 courses, each having an instructor (ForeignKey) and a list of enrolled student tags (ManyToMany). The original code fires 101 queries. Write the optimized query using select_related and prefetch_related.
# Solution to Lab 11:
courses = Course.objects.select_related('instructor__user')\
.prefetch_related('enrolled_students__profile')\
.filter(is_active=True)[:50]
# Reduced from 101 database round-trips to exactly 2 batch queries!
Problem: Build a custom middleware that calculates how many milliseconds each HTTP request takes to process and adds an X-Response-Time-Ms header to the HTTP response.
# Solution to Lab 14:
import time
class ResponseTimingMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
start_time = time.perf_counter()
response = self.get_response(request)
duration = (time.perf_counter() - start_time) * 1000 # Convert to ms
response['X-Response-Time-Ms'] = f"{duration:.2f}ms"
return response
Broaden your backend architecture, REST API design, and production engineering expertise:
Apply individual coding challenges into a unified end-to-end platform.
Pair hands-on coding practice with theoretical interview preparation.
Look up syntax and helper functions while solving coding exercises.
Prepare for practical lab examinations in university degree courses.