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

0 votes

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.

Jul 29, 2020 in Python by kartik
• 37,490 points
4,078 views

1 answer to this question.

0 votes

Hello @kartik,

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

In version Django 2.0 the syntax has changed to

request.user.is_authenticated

Hope it helps!!

Thank you!!

answered Jul 29, 2020 by Niroj
• 82,680 points

Related Questions In Python

0 votes
2 answers

How can I get the count of a list in Python?

n=[1,2,3,4,5,6,7,8,9] print(len(n)) =9 READ MORE

answered Dec 10, 2020 in Python by anonymous
395 views
0 votes
1 answer

How can I get the absolute URL (with domain) in Django?

Hello @kartik, Use handy request.build_absolute_uri() method on request, pass it ...READ MORE

answered Aug 6, 2020 in Python by Niroj
• 82,680 points
3,058 views
+1 vote
1 answer

How to get the currently logged in user's user id in Django?

Hello @kartik, First make sure you have SessionMiddleware and AuthenticationMiddleware middlewares added ...READ MORE

answered Aug 12, 2020 in Python by Niroj
• 82,680 points
7,659 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,680 points
741 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,680 points
301 views
0 votes
1 answer

How can I get the domain name of my site within a Django template?

Hello kartik, The variation of the context processor ...READ MORE

answered Apr 23, 2020 in Python by Niroj
• 82,680 points
3,196 views
0 votes
1 answer

How can I get all the request headers in Django?

Hello @kartik,  You can use request.headers to access the HTTP ...READ MORE

answered Jun 30, 2020 in Python by Niroj
• 82,680 points
3,014 views