Recall & Review
beginner
What is middleware in Django?
Middleware is a way to process requests and responses globally before they reach the view or after the view has processed them. It acts like a middle step in the request-response cycle.
Click to reveal answer
intermediate
How do you create a custom middleware class in Django?Create a class with an __init__ method and a __call__ method that takes the request and returns a response. You can also define process_view, process_exception, or process_template_response methods for specific hooks.Click to reveal answer
beginner
Where do you add your custom middleware so Django uses it?
Add the full Python path of your middleware class to the MIDDLEWARE list in the settings.py file. Django processes middleware in the order listed.Click to reveal answer
intermediate
What is the purpose of the __call__ method in Django middleware?
The __call__ method is called for each request. It receives the request, can modify it, calls the next middleware or view, and then can modify the response before returning it.
Click to reveal answer
beginner
Give a simple example of a custom middleware that prints 'Hello' for every request.
class HelloMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
print('Hello')
response = self.get_response(request)
return responseClick to reveal answer
What method must a Django middleware class implement to process each request?
✗ Incorrect
In modern Django middleware, the __call__ method is used to process each request and response.
Where do you register your custom middleware in a Django project?
✗ Incorrect
Custom middleware classes are added to the MIDDLEWARE list in settings.py.
What does the get_response argument in middleware's __init__ method represent?
✗ Incorrect
get_response is a callable that represents the next step in the request-response chain.
Which of these is NOT a typical use of custom middleware?
✗ Incorrect
Defining database models is done in models.py, not middleware.
In what order does Django process middleware listed in settings?
✗ Incorrect
Django processes middleware in the order they appear in the MIDDLEWARE list.
Explain how to create and register a simple custom middleware in Django.
Think about the request-response cycle and where your middleware fits.
You got /4 concepts.
Describe the role of middleware in Django's request-response cycle.
Middleware acts like a checkpoint between the browser and your views.
You got /4 concepts.