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?
from rest_framework.authtoken.models import Token
user = Token.objects.get(key='token string').user
A better method to use would be to simply call request.user
since access to the Token means an authenticated request. DjangoRestFramework gives access to request.auth
and request.user
on a successful TokenAuthentication.
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)
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()]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With