简体   繁体   中英

How to get logged in username in views.py in django

Actually i'am very new to django and python. In /templates/home.html, added {{ user.username }} it's showing currently logged in username

<p>Welcome {{ user.username }} !!!</p>

I want to get currently logged in username in views.py file. How to get username?

i tried different way but i am not get the result

  1. user = User.objects.get(username=request.user.username)
  2. username = request.GET['username']
  3. def sample_view(request): current_user = request.user print(current_user)

Please tell me, How to achieve my result.

my views.py look like this. is there any problem on my views.py

    #!python
    #log/views.py
    from django.shortcuts import render
    from django.contrib.auth.decorators import login_required
    from django.template import Context
    from contextlib import contextmanager
    # Create your views here.
    # this login required decorator is to not allow to any
    # view without authenticating
    @login_required(login_url="login/")
    def home(request):
         return render(request,"home.html")
#dummy_user = {{ username }}
#user = User.objects.get(username=request.user.username)
#username = request.GET['username']
#print(usernam
#user = request.user
#print(user)

    def sample_view(request):
            current_user = {}
            #current_user['loggeduser'] = request.user
             #or
            current_user['loggeduser'] = request.user.username
            return render(request,"home.html",current_user)
           # print(current_user.id)

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:

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