Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 627
Cris Towi Avatar asked Jun 03 '13 21:06

Cris Towi


People also ask

How can I see the username as logged in Django?

get_username() will return a string of the users email. request. user. username will return a method.

How do I find my Django username and password?

You can't manually check the password. Because when you are creating a user, django is storing the user's password as a hash value in the database. Now if you are storing the raw password in your custom table which is myuser , it's not a good practice.

How do you show logged in user information in Python?

Try looking into Flask-Login where you can access the logged in user's attributes via current_user i.e {{ current_user. username }} . Another option would be saving it in Flask's session then {{ session["username"] }} .


2 Answers

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 
like image 193
karthikr Avatar answered Oct 10 '22 13:10

karthikr


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 }}

like image 25
user Avatar answered Oct 10 '22 13:10

user