Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object of type 'AuthToken' is not JSON serializable

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

like image 334
kzrfaisal Avatar asked Apr 13 '19 17:04

kzrfaisal


3 Answers

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]

like image 145
Rasika Weragoda Avatar answered Nov 10 '22 00:11

Rasika Weragoda


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
})
like image 36
Radesh Avatar answered Nov 09 '22 23:11

Radesh


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]
like image 2
raven404 Avatar answered Nov 10 '22 01:11

raven404