djangodjango-rest-frameworkjwtrestful-authenticationdjango-rest-framework-jwt

Django Rest with JWT ,Getting AttributeError: Invalid API setting: 'JWT_PAYLOAD_HANDLER'


I am following this tutorial (https://medium.com/@dakota.lillie/django-react-jwt-authentication-5015ee00ef9a) to implement JWT based authentication in Django. However, I keep getting error which I am unable to figure out.

I have followed backwards to see if object being returned is use or not.

Serializer class:

class UserSerializerWithToken(serializers.ModelSerializer):
    token = serializers.SerializerMethodField()
    password = serializers.CharField(write_only=True)

    def get_token(self, obj):
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(obj)
        token = jwt_encode_handler(payload)
        return token

    def create(self, validated_data):
        password = validated_data.pop('password', None)
        instance = self.Meta.model(**validated_data)
        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance

    class Meta:
        model = User
        fields = ('token','username','password')

View for same:

class Users(APIView):
    """
    Create new user.
    """

    permission_classes = (permissions.AllowAny,)

    def post(self, request, format=None):
        serializer = UserSerializerWithToken(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

It should return token in JSON format however, error I am getting is:

AttributeError at /api/users/

Invalid API setting: 'JWT_PAYLOAD_HANDLER'

Request Method:     POST
Request URL:    http://127.0.0.1:8000/api/users/
Django Version:     2.1.7
Exception Type:     AttributeError
Exception Value:    

Invalid API setting: 'JWT_PAYLOAD_HANDLER'

Exception Location:     $/venv/lib/python3.7/site-packages/rest_framework/settings.py in __getattr__, line 216
Python Executable:  $/venv/bin/python

User is created in my database but it throws error for token generation. I am not very expert on this. Thanks !


Solution

  • I change it to from rest_framework_jwt.settings import api_settings