Venkatesh Panabaka
Venkatesh Panabaka

Reputation: 2154

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)

Upvotes: 3

Views: 11372

Answers (1)

e4c5
e4c5

Reputation: 53774

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:

Upvotes: 11

Related Questions