0
0
Djangoframework~30 mins

Creating custom middleware in Django - Try It Yourself

Choose your learning style9 modes available
Creating custom middleware
📖 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 each time a user visits any page.
📋 What You'll Learn
Create a middleware class named LogRequestMiddleware
Add an __init__ method that accepts get_response
Implement a __call__ method that logs the request path using print
Return the response from the middleware
Add the middleware to the MIDDLEWARE list in settings.py
💡 Why This Matters
🌍 Real World
Custom middleware is useful for adding features like logging, authentication checks, or modifying requests and responses in Django applications.
💼 Career
Understanding middleware helps you customize request handling and is a common task in Django web development jobs.
Progress0 / 4 steps
1
Create the middleware class
Create a class called LogRequestMiddleware with an __init__ method that takes get_response as a parameter and stores it as an instance variable.
Django
Need a hint?

Remember, the __init__ method sets up the middleware with the next callable.

2
Add the __call__ method
Add a __call__ method to LogRequestMiddleware that takes request as a parameter and calls self.get_response(request) to get the response.
Django
Need a hint?

The __call__ method processes the request and returns the response.

3
Log the request path
Inside the __call__ method, before calling self.get_response(request), add a print statement that outputs "Request path:" followed by request.path.
Django
Need a hint?

Use print("Request path:", request.path) to log the path.

4
Add middleware to settings
In settings.py, add the string 'your_app.middleware.LogRequestMiddleware' to the MIDDLEWARE list.
Django
Need a hint?

Insert 'your_app.middleware.LogRequestMiddleware' at the end of the MIDDLEWARE list.