I'm getting the above error when creating token, here's the code:
from rest_framework import generics, permissions
from rest_framework.response import Response
from knox.models import AuthToken
from .serializers import UserSerializer, RegisterSerializer
class RegisterAPI(generics.GenericAPIView):
serializer_class = RegisterSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
return Response({
"user": UserSerializer(user, context=self.get_serializer_context()).data,
"token": AuthToken.objects.create(user)
})
what am I doing wrong here
The Token.objects.create returns a tuple (instance, token). So in order to get token use the index 1
"token": AuthToken.objects.create(user)[1]
Better way is use this method in python
_, token = AuthToken.objects.create(user)
return Response({
"user": UserSerializer(user, context=self.get_serializer_context()).data,
"token": token
})
This particular error occurs because the Token.objects.create returns a tuple (instance, token). just use the second position [1] by using instead of former
"token": AuthToken.objects.create(user)[1]
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