Get user object from token string in DRF?

后端 未结 5 963
逝去的感伤
逝去的感伤 2021-02-09 16:36

I have a token string from Django REST Framework\'s TokenAuthentication.

I need to get the corresponding user object. How would I go about doing this?

5条回答
  •  Happy的楠姐
    2021-02-09 16:51

    If you invoke the user object directly from the Token class, as presented in @aliva's solution, you will get a raw partial Django User with just the fields living in the database. If you need to get the real user object, with e.g. its computed properties, you can do this:

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

提交回复
热议问题