Home > OS >  Get current Logged in User in django Rest Framework
Get current Logged in User in django Rest Framework

Time:12-14

I am trying to get current logged in user and upload/send information to frontend. I am new to Rest Framework so forgive my basic level question.

I have tried fetching user with request.user and request.auth in my views but I am not able to simply get user. This is my views.py

from rest_framework.authtoken.models import Token

def get_User (request):
    # current_user = request.user
    # context = {"user": current_user}
    # print(request.user.username)

    user_id = Token.objects.get(key=request.auth.key).user_id
    print(request.auth)

    # Response(context)

I am using a custom user model to store data.

Every time I am running request.auth or request.user i can see in my django terminal that it keeps going to /verify-auth-token/ URL.

How do I get user printed also sent to frontend in React to display in app as well. Any help is appreciated.

Edit 1: I am passing user from above mentioned view only.

from rest_framework.authtoken.models import Token
user_id = Token.objects.get(key=request.auth.key).user_id
user = Users.object.get(id =user_id)

Response (user)

This is how I think I should be passing variable to frontend but I am not getting anything achieved this way.

CodePudding user response:

If you are working with DRF and you want to pass information to your frontend, you cannot use request.user since request is working with sessions.

To identify an user you need to associate a token with an user and then pass the associate object user to your frontend and the other way around so a quick example :

def get_user_by_token(token):
 user_id = Token.objects.get(key=request.auth.key).user_id
 user = Users.object.get(id =user_id)
 return JsonResponse({"user": user.id})

So you can return whatever you want in a JSON format to your frontend once the user is associated with the token

CodePudding user response:

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)

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

  • Related