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?
Suppose you wanna get userid and username when obtain auth token in Django Rest Framework
More info can get from https://www.django-rest-framework.org/api-guide/authentication/#by-exposing-an-api-endpoint
# in views.py
from rest_framework.auth.models import Token
from rest_framework.auth.views import ObtainToken
from rest_framework.response import Response
class MyObtainToken(ObtainToken):
"""Return User Info along with token"""
def post(self, request, *arg, **kwarg)
serializer = self.serializer_class(request.data, context={'request':request})
serializer.is_valid(raise_exception=True)
user = serializer.valided_data['user']
token, _ = Token.objects.get_or_create(user)
return Response(
{
'token': token.key,
'username': user.username,
'userid': user.pk
})
# in urls.py
urlpatterns += [path(r'api/obtain_auth_token', MyObtainToken.as_view()]