Get user object from token string in DRF?

后端 未结 5 854
说谎
说谎 2021-02-09 16:01

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条回答
  •  有刺的猬
    2021-02-09 16:59

    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)
    

提交回复
热议问题