Django 4.0.2 | Python 3.9.7 | TypeError: __init__() missing 1 required positional argument: 'get_response'

Question:

I wrote a custom authentication and added a csrf check middleware in the authentication process.
I am calling the below function in the authentication function.

def enforce_csrf(self, request):
    """
    Enforce CSRF validation
    """
    check = CSRFCheck()
    check.process_request(request)
    reason = check.process_view(request, None, (), {})
    if reason:
        # CSRF failed, bail with explicit error message
        raise PermissionDenied('CSRF Failed: %s' % reason)

The CSRFCheck() function is a custom middleware and it looks like this.

class CSRFCheck(CsrfViewMiddleware):
    def _reject(self, request, reason):
        return reason

Now when I am trying to process the request, which requires authentication, I am getting the error:
TypeError: init() missing 1 required positional argument: ‘get_response’

the same code is working perfectly in Django 3.2

Now, as far as I was able to debug, the CSRFCheck function is expecting a get_response method which I don’t know where it is coming from.
get_response argument error

Asked By: Mahesh Gupta

||

Answers:

It would seem that the API for creating custom middleware is that you provide a get_response parameter upon initialization.

https://docs.djangoproject.com/en/4.0/topics/http/middleware/#writing-your-own-middleware

When you call CSRFCheck() you aren’t providing it that parameter so when it runs, it fails.

You can try following the example in the link above and reformatting your custom middleware to match the example they provided.

Answered By: Artisan

Downgrade the Django version to 3.2.X till the bug is fixed.

Answered By: Mahesh Gupta

Dowgrading to django 3.2.x works for now.

Answered By: Gajendra D Ambi