Complete the code to add a middleware class to the Django settings.
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
[1],
'django.middleware.common.CommonMiddleware',
]The SessionMiddleware manages sessions and is commonly added in the middleware list.
Complete the middleware method to process a request in a custom middleware class.
class CustomMiddleware: def __init__(self, get_response): self.get_response = get_response def [1](self, request): # Code to run before view response = self.get_response(request) # Code to run after view return response
The __call__ method is used in Django middleware classes to process requests and responses.
Fix the error in the middleware to correctly modify the response headers.
class HeaderMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) response.[1]['X-Custom-Header'] = 'Value' return response
The headers attribute is used to access and modify HTTP headers in Django HttpResponse objects.
Fill both blanks to create a middleware that blocks requests from a specific IP address.
class BlockIPMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.META.get('[1]') == '[2]': from django.http import HttpResponseForbidden return HttpResponseForbidden('Forbidden') return self.get_response(request)
The REMOTE_ADDR key in request.META holds the client's IP address. Blocking 127.0.0.1 denies localhost requests.
Fill all three blanks to write a middleware that adds a custom header only for authenticated users.
class AuthHeaderMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if request.[1].[2]: response.[3]['X-User-Status'] = 'Authenticated' return response
Access request.user.is_authenticated to check if the user is logged in, then add the header via response.headers.