Django没有为AnonymousUser提供数据库表示-Django Rest API

时间:2019-10-29 04:18:22

标签: python django django-models django-rest-framework

我尝试不使用传统方式更改密码。输入旧密码和新密码,更新旧密码。我使用了UpdateApiView。但是出现以下错误。

Django doesn't provide a DB representation for AnonymousUser

我使用POST MAN在标头中尝试了passigng 授权令牌。但是同样的错误。

view.py

class ChangePassword(generics.UpdateAPIView):
    serializer_class = serializers.ChangePasswordSerializer
    model = models.Customer

    def get_object(self, queryset=None):
        obj = self.request.user
        return obj

    def update(self, request, *args, **kwargs):
        self.object = self.get_object()
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():

            if not self.object.check_password(serializer.data.get("old_password")):
                return Response({"old_password": ["Wrong password."]}, status=HTTP_400_BAD_REQUEST)

            self.object.set_password(serializer.data.get("new_password"))
            self.object.save()
            return Response("Success.", status=HTTP_200_OK)

        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

serializers.py

class ChangePasswordSerializer(serializers.Serializer):


    old_password = serializers.CharField(required=True)
    new_password = serializers.CharField(required=True)

urls.py

 path('update_password', views.ChangePassword.as_view()),

编辑: 我在settings.py

中添加了TokenAuthentication
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    )
}

在views.py中,我添加了 authentication_classes =(令牌认证,)

现在我得到了name 'TokenAuthentication' is not defined

我在views.py中导入了TokenAuthentication

from rest_framework.authentication import SessionAuthentication, TokenAuthentication

但是Django doesn't provide a DB representation for AnonymousUser.

1 个答案:

答案 0 :(得分:0)

将属性authentication_classes = (TokenAuthentication, )添加到ChangePassword视图。