Complete the code to define a middleware class with the correct method name.
class SimpleMiddleware: def [1](self, request): print("Middleware called") return None
The method process_request is used in Django middleware to process the request before the view is called.
Complete the code to call the next middleware or view in the chain.
class CustomMiddleware: def __init__(self, get_response): self.get_response = [1] def __call__(self, request): response = self.get_response(request) return response
get_response to a local variable instead of an instance variable.The __init__ method stores the get_response callable in self.get_response to call it later.
Fix the error in the middleware method to correctly modify the response.
class HeaderMiddleware: def __call__(self, request): response = self.get_response(request) response.[1]['X-Custom-Header'] = 'Hello' return response
header instead of headers.In Django, the response headers are accessed via the headers attribute, which acts like a dictionary.
Fill both blanks to create a middleware that logs the request path and then calls the next middleware.
class LoggingMiddleware: def __init__(self, [1]): self.get_response = [2] def __call__(self, request): print(f"Request path: {request.path}") response = self.get_response(request) return response
request as the constructor parameter.self.get_response.The constructor takes get_response as a parameter and assigns it to self.get_response to call it later.
Fill all three blanks to create a middleware that adds a custom header only for GET requests.
class CustomHeaderMiddleware: def __init__(self, [1]): self.get_response = [2] def __call__(self, request): response = self.get_response(request) if request.method == [3]: response.headers['X-Method'] = 'GET' return response
'POST' instead of 'GET'.The constructor takes get_response and assigns it to self.get_response. The condition checks if the request method is the string 'GET'.