[Django]-How to get logged in username in views.py in django

10👍

Provided that you have enabled the authentication middleware, you don’t need to do any of this. The fact that the username shows up in your template indicates that you have enabled it. Each view has access to a request.user that is an instance of a User model. So the following is very much redundant

user = User.objects.get(username=request.user.username)

Because you already have request.user.username!! if you wanted to find the user’s email, you do request.user.email Or just do

user = request.user 

and use the newly created variable (eg user.username)

Reference: https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest.user

From the AuthenticationMiddleware: An instance of AUTH_USER_MODEL
representing the currently logged-in user. If the user isn’t currently
logged in, user will be set to an instance of AnonymousUser. You can
tell them apart with is_authenticated, like so:

👤e4c5

Leave a comment