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,520 points
37,100 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,840 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,840 points
3,174 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,840 points
13,695 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,460 points
1,373 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,840 points
2,449 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,840 points
1,564 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,840 points
10,780 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,840 points
6,050 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