简体   繁体   中英

How to check which user is logged in with Django?

I am currently working on a website, and I wanted to know how do I check which user is logged in. Just to clarify I am using the Django built in models from django.contrib.auth.models import User to do my login, logout etc. What I don't know how to do is check which user is logged in, I know the method

if user.is_authenticated:
    # Other code goes here

But this method only checks weather the user is logged in not which user is logged in?

You can find info about the logged user in the request.user method

Here an example if you want to know the username:

username = request.user.username

If you make use of the AuthenticationMiddleware [Django-doc] (this is the default if you create a new project), then this middleware will add a .user attribute [Django-doc] to the request. This is a lazy loaded user model object, or the AnonymousUser [Django-doc] if the user has not logged in.

But if tyhe user thus has logged in, this is a user model object just like any other. You thus can access fields, methods, etc. from that object, and use it when you create an object to let a ForeignKey refer to that user.

If you for example use the default User model [Django-doc] , then you can access attributes like request.user.first_name , request.user.last_name , request.user.username , etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM