0
0
Djangoframework~10 mins

Creating custom middleware in Django - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a middleware class with the correct method name.

Django
class SimpleMiddleware:
    def [1](self, request):
        print("Middleware called")
        return None
Drag options to blanks, or click blank then click option'
Amiddleware_call
Bhandle_request
Cprocess_request
Dprocess_response
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'process_response' instead of 'process_request'.
Using a method name not recognized by Django middleware.
2fill in blank
medium

Complete the code to call the next middleware or view in the chain.

Django
class CustomMiddleware:
    def __init__(self, get_response):
        self.get_response = [1]

    def __call__(self, request):
        response = self.get_response(request)
        return response
Drag options to blanks, or click blank then click option'
Arequest
Bget_response
Cresponse
Dself.get_response
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning get_response to a local variable instead of an instance variable.
Using the wrong variable name.
3fill in blank
hard

Fix the error in the middleware method to correctly modify the response.

Django
class HeaderMiddleware:
    def __call__(self, request):
        response = self.get_response(request)
        response.[1]['X-Custom-Header'] = 'Hello'
        return response
Drag options to blanks, or click blank then click option'
Aadd_header
Bheader
Cset_header
Dheaders
Attempts:
3 left
💡 Hint
Common Mistakes
Using header instead of headers.
Trying to call a method that doesn't exist.
4fill in blank
hard

Fill both blanks to create a middleware that logs the request path and then calls the next middleware.

Django
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
Drag options to blanks, or click blank then click option'
Aget_response
Brequest
Cresponse
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Using request as the constructor parameter.
Assigning the wrong variable to self.get_response.
5fill in blank
hard

Fill all three blanks to create a middleware that adds a custom header only for GET requests.

Django
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
Drag options to blanks, or click blank then click option'
Aget_response
Bself.get_response
C'GET'
D'POST'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'POST' instead of 'GET'.
Mixing up the parameter and instance variable names.