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

Cris Towi picture Cris Towi · Jun 3, 2013 · Viewed 133.8k times · Source

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.

Thanks. =)

Answer

karthikr picture karthikr · Jun 4, 2013

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