Django middleware: Isn't a middleware module error
-
28-10-2019 - |
Question
I am using the middleware provided in https://gist.github.com/426829 to do cross site scripting.
However, when I add the middleware to MIDDLEWARE_CLASSES
, I get the error:
ImproperlyConfigured: isn't a middleware module.
My MIDDLEWARE_CLASSES
looks like this:
MIDDLEWARE_CLASSES = ('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'TempMiddleware',)
I have not changed any code in the gist. process_request
and process_response
methods are there. I am on Ubuntu running the latest versions of Python and Django.
Solution
What's TempMiddleware
? The name of the module, or the name of the class? As you can see with the other entries, you need the fully-qualified Python path of the actual class. If TempMiddleware
is the name of the module, you need TempMiddleware.MyMiddlewareClass
(and you should really follow PEP8 naming conventions) - and if it's the name of the class, you need my_module.TempMiddleware
.
OTHER TIPS
Edit:
TempMiddleware
is not importable. It's the name of the class, you must put the entire import path.
E.g:
'django.contrib.auth.middleware.AuthenticationMiddleware'
and not
'AuthenticationMiddleware'
So if your class is in app_name/middleware.py, it should be
app_name.middlaware.TempMiddleware
It just mean that in your settings file, the variable MIDDLEWARE_CLASSES
contains a list of modules in which one of the listed module is not a middleware.
Possible causes:
- you added a middleware that doesn't declare middleware methods: fix that by removing the last middleware you added
- you added a correct middleware but forget to put a coma at the end of the name, so strings are concatenated and it make django thinks 2 middlewares are in fact one: fix that by adding the missing coma