Get the user object from session

Question:

How can I get the user object that login() has save in the session?

user= request.session.get('user') 

returns nothingIn this example:

user = authenticate(username=username, password=password)
if user is not None:
    if user.is_active:
        login(request, user)
Asked By: hln

||

Answers:

AuthenticationMiddleware adds the user attribute, representing the currently-logged-in user, to every incoming HttpRequest object. Authentication middleware requires session middleware to be installed. So, you should add this middlewares in settings.py to MIDDLEWARE_CLASSES tuple:

MIDDLEWARE_CLASSES = ( 
    #...
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    #...
)
Answered By: ndpu

Make sure you have ‘django.contrib.auth‘ and ‘django.contrib.contenttypes‘ in your installed apps. run syncdb if needed after. Now you will have all the user tables you need.

Next you want to make sure you have request.user on every request. I think this is why your not getting anything with request.user. SessionMiddleware and AuthenticationMiddleware middlewares needs to be in your MIDDLEWARE_CLASSES in settings.

For more info read the docs here

Answered By: Glyn Jackson
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.