Search code examples
djangodjango-rest-frameworkdjango-authentication

Object of type Token is not JSON serializable


views.py this is my views.py. when I wanna login I get an error.

class AuthAPIView(APIView):
    def post(self, request, format=None):
        data = request.data

        username = data.get('username', None)
        password = data.get('password', None)

        user = authenticate(username=username, password=password)

        if user is not None:
            if user.is_active:
                login(request, user)
                token = Token.objects.get(user=user)
                return Response(token)
            else:
                return Response(status=status.HTTP_404_NOT_FOUND)
        else:
            return Response(status=status.HTTP_404_NOT_FOUND)

I have created a token for each user when registering. and now when I wanna authenticate I get an error. I wanna get my Token instead.


Solution

  • You are returning a Token model object which is not JSON serializable. Not sure what is the structure of your Token model. If you just want to return a string token, then only return that and not the entire Token object. If you want to return the complete Token object, you can create a Serializer for the Token model and use that to serialize the Token object and return it.