Reputation: 1774
I need to modify response object in middleware, so i have added 'myproject.common.middlware.ResponseMiddleware'
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware', # order matters don't move
'django.middleware.gzip.GZipMiddleware', # order matters don't move
'django.middleware.locale.LocaleMiddleware', # order matters don't move
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'myproject.common.middleware.ResponseMiddleware',
)
However in my ResponseMiddleware, I have the code below:
class ResponseMiddleware(object):
def process_response(self, request, response):
if 'status_code' not in response:
response['status_code'] = 200
return response
However, response.status_code cannot be found in other middlewares such as django's CommonMiddleware. I use Django 1.4 and from the document, order to process_response is reversed order of the order defined in MIDDLEWARE_CLASSES. So I put mine to the very bottom.
and i get
AttributeError: 'dict' object has no attribute 'status_code' from other Middleware.
(*** this is related to WebSocket generates error in django common middleware)
Upvotes: 1
Views: 904
Reputation: 1291
The problem is that your middleware is being executed the first one with process_response
.
process_request
and process_view
methods are executed from the top to the bottom of the list, but process_response
is executed from the bottom to the top. Check the following graph from Django documentation:
https://docs.djangoproject.com/en/dev/topics/http/middleware/#hooks-and-application-order
So, if you put your middleware the first on the list, it should work.
Upvotes: 1