首页 > 解决方案 > Django 没有为 AnonymousUser- Django rest api 提供数据库表示

问题描述

我尝试不使用传统方式更改密码。给出旧密码和新密码,更新旧密码。我使用了 UpdateApiView。但我收到以下错误。

Django doesn't provide a DB representation for AnonymousUser

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

视图.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)

序列化程序.py

class ChangePasswordSerializer(serializers.Serializer):


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

网址.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 = (TokenAuthentication, )

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

我在 views.py 中导入了 TokenAuthentication

from rest_framework.authentication import SessionAuthentication, TokenAuthentication

Django doesn't provide a DB representation for AnonymousUser.

标签: pythondjangodjango-modelsdjango-rest-framework

解决方案


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


推荐阅读