0
0
Djangoframework~30 mins

Middleware configuration in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Middleware configuration
📖 Scenario: You are building a Django web application that needs to log every request's path for debugging purposes.
🎯 Goal: Create a custom middleware that logs the request path, then add it to the Django project's middleware settings.
📋 What You'll Learn
Create a custom middleware class named LogRequestMiddleware in a file called middleware.py inside an app named core.
The middleware must have a __call__ method that logs the request path using print().
Add the core.middleware.LogRequestMiddleware to the MIDDLEWARE list in settings.py after django.middleware.common.CommonMiddleware.
💡 Why This Matters
🌍 Real World
Middleware is used in Django projects to add functionality that runs on every request, such as logging, authentication, or security checks.
💼 Career
Understanding middleware configuration is essential for backend developers working with Django to customize request handling and add cross-cutting features.
Progress0 / 4 steps
1
Create the middleware class
In the core/middleware.py file, create a class called LogRequestMiddleware with an __init__ method that accepts get_response and stores it as an instance variable.
Django
Need a hint?

Middleware classes in Django need an __init__ method that takes get_response and saves it.

2
Add the __call__ method to log request path
Add a __call__ method to LogRequestMiddleware that takes request, prints request.path, then returns the response by calling self.get_response(request).
Django
Need a hint?

The __call__ method processes each request. Use print(request.path) to log the path.

3
Open settings.py and locate MIDDLEWARE list
Open settings.py and find the MIDDLEWARE list variable. Do not change it yet.
Django
Need a hint?

The MIDDLEWARE list is usually near the top of settings.py.

4
Add custom middleware to MIDDLEWARE list
Add the string 'core.middleware.LogRequestMiddleware' to the MIDDLEWARE list in settings.py immediately after 'django.middleware.common.CommonMiddleware'.
Django
Need a hint?

Insert your middleware string right after 'django.middleware.common.CommonMiddleware' in the list.