3

According to the Django documentation, the HttpRequest object has a "user" attribute that represents the currently logged in user if the Django installation has activated AuthenticationMiddleware. How does the request object know what the user is? Does the middleware set the user in a cookie and save that cookie to the client browser after the user logs in? In my code, I save the user's ID (from the auth_user table) to a session variable after they've logged in and I usually examine it on each page. If this information is always available in the request object, I shouldn't need to do this. All I should need to do is examine request.user.id. Is this correct?

Thanks.

2 Answers 2

0

Yes you've got it, except the user data is stored in the session. You're doing redundant work by keeping track off all that yourself - this something Django is great at! Check out this documentation on user objects .. and this article on all of it specifically.

0

User id is stored not in the cookie but in the session.

And yes, you shouldn't save this data in the session by yourself:

if request.user.is_authenticated():
    user_id = request.user.id

If the view should be available for logged users only then instead of checking of request.user.is_authenticated() use the @login_required decorator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.