Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'WSGIRequest' object has no attribute 'session'

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?

like image 650
sunprophit Avatar asked Aug 02 '12 18:08

sunprophit


2 Answers

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).

like image 178
sunprophit Avatar answered Oct 25 '22 19:10

sunprophit


If you came here because you updated to Django 2.0 and get this error, you might want to know that name MIDDLEWARE_CLASSES was replaced with MIDDLEWARE.

More here https://stackoverflow.com/a/47650447/1218179 and here https://docs.djangoproject.com/en/2.0/topics/http/middleware/

like image 43
mateuszb Avatar answered Oct 25 '22 19:10

mateuszb