【发布时间】:2019-11-04 12:39:53
【问题描述】:
我需要在 DRF 中准备一个允许更改用户密码的端点。所以我读了这篇文章: How to update user password in Django Rest Framework?
但是,老实说,即使在阅读了那篇文章并在我的应用程序中实现了那篇文章中的代码之后,它仍然无法正常工作。我是 Django 和 Python 的新手,我不明白我做错了什么。你能帮我理解我做错了什么吗?
下面是我实现的代码:
序列化器.py
from rest_framework import serializers
class ChangePasswordSerializer(serializers.Serializer):
"""
Serializer for password change endpoint.
"""
old_password = serializers.CharField(required=True)
new_password = serializers.CharField(required=True)
api.py
# Password Change API
class ChangePasswordAPI(generics.UpdateAPIView):
"""
An endpoint for changing password.
"""
serializer_class = ChangePasswordSerializer
model = User
permission_classes = (IsAuthenticated,)
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():
# Check old password
if not self.object.check_password(serializer.data.get("old_password")):
return Response({"old_password": ["Wrong password."]}, status=status.HTTP_400_BAD_REQUEST)
# set_password also hashes the password that the user will get
self.object.set_password(serializer.data.get("new_password"))
self.object.save()
return Response("Success.", status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
urls.py
from django.urls import path, include
from .api import ChangePasswordAPI
from django.conf.urls import url
urlpatterns = [
url(r'^auth/password-change/(?P<pk>[0-9]+)$', ChangePasswordAPI.as_view()),
]
所以现在我将 PUT 发送到 http://localhost:8000/auth/change-password/ 带有以下正文:
{
"old_password": "password1",
"new_password": "password2"
}
我收到这条消息:
<h1>Not Found</h1>
<p>The requested resource was not found on this server.</p>
【问题讨论】:
标签: python django-rest-framework