python - 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.
解决方案
将属性添加authentication_classes = (TokenAuthentication, )
到 ChangePassword 视图。
推荐阅读
- javascript - Rally SDK 2 - 如何将故事附加到功能
- android - Android Studio:更新后 Gradle 项目同步失败
- php - MYSQL:INSERT INTO 同时也在同一个查询中进行 INNER JOIN
- python - PYTHON - 我的列表加法器函数不想传递给另一个函数
- constants - 依赖类型签名中的多态常量?
- python - 如何将 matplotlib 图形输出缩放到 A3?
- python - 为什么我无法抓取我的 Facebook 主页?
- entity-framework-core - EF Core TPH 鉴别器忽略基本实体
- reactjs - 如何明确替换 componentWillReceiveProps 并不断获取 nextProps?
- javascript - jqxGrid 未从 PHP 生成的 JSON 填充