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

0 votes

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 in Python by kartik
• 27,140 points
286 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 by Niroj
• 58,500 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 in Python by Niroj
• 58,500 points
79 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 in Python by Niroj
• 58,500 points
277 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,380 points
258 views
0 votes
3 answers

How to get the current time in Python

FOLLOWING WAY TO FIND CURRENT TIME IN ...READ MORE

answered Apr 8, 2019 in Python by rajesh
• 1,230 points
275 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 in Python by Niroj
• 58,500 points
179 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 in Python by Niroj
• 58,500 points
80 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 in Python by Niroj
• 58,500 points
261 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 in Python by Niroj
• 58,500 points
112 views