181

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

In models.py:

class Game(models.model):
    name = models.CharField(max_length=255)
    owner = models.ForeignKey(User, related_name='game_user', verbose_name='Owner')

In views.py:

gta = Game.objects.create(name="gta", owner=?)
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
k44
  • 1,855
  • 3
  • 13
  • 7

8 Answers8

309

First make sure you have SessionMiddleware and AuthenticationMiddleware middlewares added to your MIDDLEWARE_CLASSES setting.

The current user is in request object, you can get it by:

def sample_view(request):
    current_user = request.user
    print current_user.id

request.user will give you a User object representing the currently logged-in user. If a user isn't currently logged in, request.user will be set to an instance of AnonymousUser. You can tell them apart with the field is_authenticated, like so:

if request.user.is_authenticated:
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
jperezmartin
  • 407
  • 4
  • 19
K Z
  • 29,661
  • 8
  • 73
  • 78
29

You can access Current logged in user by using the following code:

request.user.id
8

Assuming you are referring to Django's Auth User, in your view:

def game(request):
  user = request.user

  gta = Game.objects.create(name="gta", owner=user)
Neil
  • 7,042
  • 9
  • 43
  • 78
2

FROM WITHIN THE TEMPLATES

This is how I usually get current logged in user and their id in my templates.

<p>Your Username is : {{user}} </p>
<p>Your User Id is  : {{user.id}} </p>
Mujeeb Ishaque
  • 2,259
  • 24
  • 16
0

I wrote this in an ajax view, but it is a more expansive answer giving the list of currently logged in and logged out users.

The is_authenticated attribute always returns True for my users, which I suppose is expected since it only checks for AnonymousUsers, but that proves useless if you were to say develop a chat app where you need logged in users displayed.

This checks for expired sessions and then figures out which user they belong to based on the decoded _auth_user_id attribute:

def ajax_find_logged_in_users(request, client_url):
    """
    Figure out which users are authenticated in the system or not.
    Is a logical way to check if a user has an expired session (i.e. they are not logged in)
    :param request:
    :param client_url:
    :return:
    """
    # query non-expired sessions
    sessions = Session.objects.filter(expire_date__gte=timezone.now())
    user_id_list = []
    # build list of user ids from query
    for session in sessions:
        data = session.get_decoded()
        # if the user is authenticated
        if data.get('_auth_user_id'):
            user_id_list.append(data.get('_auth_user_id'))

    # gather the logged in people from the list of pks
    logged_in_users = CustomUser.objects.filter(id__in=user_id_list)
    list_of_logged_in_users = [{user.id: user.get_name()} for user in logged_in_users]

    # Query all logged in staff users based on id list
    all_staff_users = CustomUser.objects.filter(is_resident=False, is_active=True, is_superuser=False)
    logged_out_users = list()
    # for some reason exclude() would not work correctly, so I did this the long way.
    for user in all_staff_users:
        if user not in logged_in_users:
            logged_out_users.append(user)
    list_of_logged_out_users = [{user.id: user.get_name()} for user in logged_out_users]

    # return the ajax response
    data = {
        'logged_in_users': list_of_logged_in_users,
        'logged_out_users': list_of_logged_out_users,
    }
    print(data)

    return HttpResponse(json.dumps(data))

ViaTech
  • 2,143
  • 1
  • 16
  • 51
0

This is how I usually get current logged in user and their id in my templates.

<p>Your Username is : {{user|default: Unknown}} </p>
<p>Your User Id is  : {{user.id|default: Unknown}} </p>
0

Just go on your profile.html template and add a HTML tag named paragraph there,

<p>User-ID: {% user.id %}</p>
0

You can use HttpRequest.user and get_user(request) to get the id of the logged-in user in Django Views as shown below:

# "views.py"

from django.shortcuts import render
from django.contrib.auth import get_user # Here

def test(request):
    print(request.user.id) # 32
    print(get_user(request).id) # 32
    return render(request, 'index.html')

And, you can get the id of the logged-in user in Django Templates as shown below:

{% "index.html" %}

{{ user.id }} {% 32 %}
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129