I want to create a new module and set of middleware classes in my app. I created a subfolder "middleware" and put my python classes there in separate files. But when I try to access them it says not defined.
For the following to work where do I place my 'CustomerMiddleware' class and what else do I need to do?
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'dose.middleware.CustomMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CodePudding user response:
Place your middleware at the end of your middleware section
The exact reference will depend on where the files live in your directory structure, relative to your projectfolder. I keep mine in the same folder as my base URLs.py and asgi/wsgi files, so mine looks like the below
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'dose.middleware.CustomMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'projectname.middleware_filename.middlewareclass1',
'projectname.middleware_filename.middlewareclass2',
]
CodePudding user response:
I was trying to find a way to subclass a core Django class so I could change its behavior. I found out how to do it, but along the way I discovered the Django Middleware that could intercept requests and responses anywhere in the application regardless of the app. A CustomMiddleware was the key and with that I can do anything I want to do either before or after a request is handled by the model.
Here is the Middleware documentation
Enjoy.