Django Practice Exercises: 15+ Real-World Coding Challenges

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.

Tier 1: Foundations

Challenges 1 – 5 (MVT, ORM, Forms)

Tier 2: Intermediate

Challenges 6 – 10 (Auth, CBVs, Custom Managers)

Tier 3: Advanced

Challenges 11 – 15 (DRF, Celery, N+1, Middleware)

Lab 1: Build a Multi-Author Blog Model Schema

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)

Lab 6: Build a Custom QuerySet Manager for E-Commerce Inventory

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()

Lab 11: Eliminate N+1 Queries on a Course Catalog API

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!

Lab 14: Custom Middleware for Request Execution Timing

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

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. Why are hands-on coding exercises essential when learning Django?

Reading documentation gives passive knowledge, but debugging real code gives muscle memory. Building actual features — such as shopping carts, search filters, and custom authentication — exposes edge cases like query performance, CSRF tokens, and form validation.

Q2. Are solutions provided for all 15 coding exercises?

Yes. Every practice challenge includes a detailed problem statement, architectural requirements, starter hints, and a verified, idiomatic solution using modern Django 5.x conventions.

Q3. Are these exercises suitable for university lab coursework and practical exams?

Yes. The exercises are structured into three progressive difficulty tiers (Beginner, Intermediate, and Advanced) matching university practical lab syllabi for BCA, MCA, and B.Tech computer science degree programs.

Explore Related Django Tutorials & Next Steps

Broaden your backend architecture, REST API design, and production engineering expertise:

Complete Production Capstone Project

Apply individual coding challenges into a unified end-to-end platform.

130+ Django Interview Questions

Pair hands-on coding practice with theoretical interview preparation.

Django Master Cheat Sheet

Look up syntax and helper functions while solving coding exercises.

BCA/MCA University Viva Questions

Prepare for practical lab examinations in university degree courses.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!