How can I get the username of the logged-in user in Django? How can I get the username of the logged-in user in Django? python python

How can I get the username of the logged-in user in Django?


You can use the request object to find the logged in user

def my_view(request):    username = None    if request.user.is_authenticated():        username = request.user.username

According to https://docs.djangoproject.com/en/2.0/releases/1.10/

In version Django 2.0 the syntax has changed to

request.user.is_authenticated


request.user.get_username() or request.user.username, former is preferred.

Django docs say:

Since the User model can be swapped out, you should use this method instead of referencing the username attribute directly.

P.S. For templates, use {{ user.get_username }}


'request.user' has the logged in user.
'request.user.username' will return username of logged in user.