Django: WSGIRequest' object has no attribute 'user' on some pages?

Yugal Jindle picture Yugal Jindle · Jun 27, 2012 · Viewed 29.9k times · Source

I want to set a cookie if user is logged in or not.

My middleware:

class UserStatus(object):
    def process_response(self,request,response):
        user_status = 1 if request.user.is_authenticated() else 0
        max_age = (20)*52*7*24*60*60 # 20 years (After expiry, cookie gets deleted)
        response.set_cookie(user_status_cookie,user_status,max_age)
        return response

Added to MIDDLEWARE_CLASSES in settings.py at the end.

Problem:

  • Error: 'WSGIRequest' object has no attribute 'user'
  • Why, when I have the Authentication and the Session middlewares active already ?
  • Also, some pages are working smooth where as some are giving this error.
  • What am I doing wrong ?

Answer

YacineAzmi picture YacineAzmi · Feb 10, 2013

Ran into the same issue recently, and found that it happened when a url is being accessed without the trailing slash, and the APPEND_SLASH setting is set to true:


Django processes initial request

  • CommonMiddleware.process_request
    • Redirects to newurl, which has the trailing slash
  • process_response is still run in custom middleware
    • request.user is not present
  • HTTP 301

Django then processes the request of url with trailing slash

  • process_response is run in custom middleware
    • request.user is now present

Anyone knows why some of the main attributes (user and session) are not accessible in process_response after a permanent redirect?