3

I am struggling getting MiddleWare to work. I put this in my settings.py:

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'portal.middleware.SimpleMiddleware'
]

and I implemented this class in portal/middleware/MiddleWare.py:

class SimpleMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response

But when running, I get a TypeError:

TypeError: __init__() takes exactly 2 arguments (1 given)
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195

1 Answers1

3

Since you are writing a new-style middleware, you should use MIDDLEWARE instead of MIDDLEWARE_CLASSES in your settings.

You also need to make sure that your entry in the settings matches the location of the middleware. The entry 'portal.middleware.SimpleMiddleware' suggests a SimpleMiddleware class in portal/middleware.py, which does not match your filename portal/middleware/MiddleWare.py.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • I did. But now nothing seems to load at all. Not even syntax errors in my `MiddleWare.py` file are caught. – Bart Friederichs Oct 03 '17 at 14:00
  • It doesn't look like you are referencing `MiddleWare.py` anywhere - your setting references `portal.middleware`. – Alasdair Oct 03 '17 at 14:06
  • 1
    Yes, and I was expecting errors that it couldn't find those. This is, I still had an old `.pyc` file still there, which provided the class. (I was experimenting and playing ...). It looks like I have it now. – Bart Friederichs Oct 03 '17 at 14:08