I get this error sometimes in custom Middleware in process_response method. I have the following list of middlewares:
MIDDLEWARE_CLASSES = [
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.doc.XViewMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'application.middleware.LastCampaignSessionMiddleware'
]
So session middleware is placed before my middleware. I don't have any del request.session
expressions in source code.
This is process_response method:
def process_response(self, request, response):
if 'last_campaign_id' in request.session and request.session['last_campaign_id']:
if request.COOKIES['last_campaign_id'] != request.session['last_campaign_id']:
response.set_cookie('last_campaign_id', request.session['last_campaign_id'])
return response
Not sure why it could happen at all.
EDIT 03-08-2012 12-30
It looks like browser requesting favicon:
[03/Aug/2012 10:26:42] "GET /favicon.ico/ HTTP/1.1" 404 6701
Is there no default behavior in django to resolve this url? Because I didn't explicitly specify view which should handle this request. And I don't use favicon in page source code. So I guess it's browser who requests /favicon.ico. I guess in case of 404 error HttpRequest wouldn't construct properly so no wonder I have no session in request object. But it's just my assumptions.
Also if it necessary I am using django dev server while getting this error.
EDIT 13-00
I have fixed this problem with favicon but still getting error. Why session may not exist in request?
The problem was in middlewares order.
CommonMiddleware returns HttpResponsePermanentRedirect in cases when to request url have been added 'www' or trailing '/' (APPEND_SLASH and PREPEND_WWW in settings). In such case django stops looking through middleware list for process_request methods and begins to run process_response methods.
It's bad there is no information about such behavior for standard django middlewares (i.e. middleware could return in some cases HttpResponse object).