2

我正在按照本教程(https://medium.com/@dakota.lillie/django-react-jwt-authentication-5015ee00ef9a)在 Django 中实现基于 JWT 的身份验证。但是,我不断收到我无法弄清楚的错误。

我已经向后看,看看返回的对象是否被使用。

序列化器类:

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')

查看相同:

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)

它应该以 JSON 格式返回令牌但是,我得到的错误是:

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

用户是在我的数据库中创建的,但它会引发令牌生成错误。我不是这方面的专家。谢谢 !

4

2 回答 2

3

I got same error. I was importing api_setting from rest_framework not rest_framework_jwt

于 2019-09-11T09:41:03.917 回答
2

我把它改成from rest_framework_jwt.settings import api_settings

于 2019-10-06T16:01:55.183 回答