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

+1 vote

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=?)
Aug 12, 2020 in Python by kartik
• 37,510 points
35,824 views

1 answer to this question.

0 votes

Hello @kartik,

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.

Hope it works!!

Thank you!!

answered Aug 12, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
1 answer

How to extend the User model with custom fields in Django?

Hello @kartik, Define an object manager for your ...READ MORE

answered Aug 3, 2020 in Python by Niroj
• 82,880 points
2,848 views
0 votes
1 answer

How to get Request.User in Django-Rest-Framework serializer?

Hello @kartik, You cannot access the request.user directly. You need ...READ MORE

answered Aug 12, 2020 in Python by Niroj
• 82,880 points
12,886 views
0 votes
1 answer

How to get the size of a string in Python?

If you are talking about the length ...READ MORE

answered Jun 4, 2018 in Python by aryya
• 7,450 points
1,082 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,880 points
2,083 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,880 points
1,230 views
0 votes
1 answer

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

Hello @kartik, You can use the request object ...READ MORE

answered Jul 29, 2020 in Python by Niroj
• 82,880 points
10,180 views
0 votes
1 answer

How to access the user profile in a Django template?

Hello @kartik, In your profile model provide related_name user ...READ MORE

answered Jul 29, 2020 in Python by Niroj
• 82,880 points
5,343 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP