[python] 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.

Thanks. =)

This question is related to python django django-templates django-views models

The answer is


For classed based views use self.request.user.id


For template, you can use

{% firstof request.user.get_full_name request.user.username %}

firstof will return the first one if not null else the second one


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


if you are using the old way of writting views, in the way of Function-Based-Views...

in your view, you are creating a new variable called usuario to save the request.user probably...

but if you returning to the Template a context_instance, passing the value of the Context of the request, you will get the logged user, just by accessing the request.

// In your views file
from django.shortcuts import render_to_response
from django.template import RequestContext
def your_view(request):
    data = {
        'formulario': Formulario()
        # ...
    }
    return render_to_response('your_template.html',
        data, context_instance=RequestContext(request))


// In your template
<form id='formulario' method='POST' action=''>
    <h2>Publica tu tuit, {{ request.user.username.title }} </h2>
    {% csrf_token %}
    {{ formulario.as_p }}
    <p><input type='submit' value='Confirmar' /></p>
</form>

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


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

request.user.username will return a method.


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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to django

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal?

Examples related to django-templates

Django - Did you forget to register or load this tag? How to add url parameters to Django template url tag? bootstrap 3 wrap text content within div for horizontal alignment Django, creating a custom 500/404 error page How can I get the username of the logged-in user in Django? Does Python have a toString() equivalent, and can I convert a db.Model element to String? How do I call a Django function on button click? What is the equivalent of "none" in django templates? Django - iterate number in for loop of a template Django -- Template tag in {% if %} block

Examples related to django-views

Unable to import path from django.urls Class has no objects member The view didn't return an HttpResponse object. It returned None instead django - get() returned more than one topic __init__() got an unexpected keyword argument 'user' How can I get the username of the logged-in user in Django? Django DoesNotExist How do I call a Django function on button click? Django optional url parameters Update only specific fields in a models.Model

Examples related to models

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model How can I get the username of the logged-in user in Django? Django: Calling .update() on a single model instance retrieved by .get()?