How can I get the username of the logged-in user in Django?
Solution 1
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
Solution 2
request.user.get_username()
or request.user.username
, former is preferred.
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 }}
Solution 3
'request.user' has the logged in user.
'request.user.username' will return username of logged in user.
Solution 4
For classed based views use self.request.user.id
Solution 5
You can use this to get the logged-in user's username :-
Just write this in template.
{{ request.user.username }}
Related videos on Youtube
Cris Towi
Updated on July 05, 2022Comments
-
Cris Towi almost 2 years
How can I get information about the logged-in user in a Django application?
For example:
I need to know the username of the logged-in user to say who posted a Review:
<form id='formulario' method='POST' action=''> <h2>Publica tu tuit, {{ usuario.username.title }} </h2> {% csrf_token %} {{formulario.as_p}} <p><input type='submit' value='Confirmar' /></p> </form>
In
usuario.username.title
I get the username, but in the template, I need to get that information from the view.-
karthikr almost 11 yearswhat is
usario
is it the user object or the userprofile ? -
Cris Towi almost 11 yearsYes, is the profile, but i need to get the username in the view to save in the model. =)
-
karthikr almost 11 yearsok. .check the answer. that is how you access the username from the view
-
-
ray6080 about 10 yearsTo use this, you must have the
request template context processor
installed in yoursettings.py
. see this -
Sathish over 9 yearsThis does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post.
-
ancho over 8 yearsit will return User object. you can get some user properties from this object.
-
Ricardo G Saraiva almost 5 yearsRequest param on method, i just use request.user.id for example
-
Mr Coder almost 3 yearsif request.user.is_authenticated(): TypeError: 'bool' object is not callable can you help on it django 3.2
-
Gathide almost 2 yearsIs 'Function-Based-Views...' an old way of writing views?
-
Luan Fonseca almost 2 yearsHi @Gathide, yea. If you see this answer is from 2013... back then the Class-based views weren't really a thing, nowadays the Request processor is pretty standard on templates and you can just use
{{ request.user.username }}
. I recommend you reading this: docs.djangoproject.com/en/4.0/topics/class-based-views/intro