如何通过API更改用户密码

我需要在DRF中准备一个端点,以允许更改用户密码。所以我读了这篇文章: How to update user password in Django Rest Framework?

但是,老实说,即使在阅读了该文章并在我的App中实现了该文章中的代码之后,它仍然无法正常工作。我是Django和Python的新手,我没弄错我做错了什么。您能帮助我了解我做错了什么吗?

以下是我实现的代码:

serializers.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()),]

所以现在我在http://localhost:8000/auth/change-password/上发送PUT 具有以下主体:

{
    "old_password": "password1","new_password": "password2"
}

我收到此消息:

<h1>Not Found</h1>
<p>The requested resource was not found on this server.</p>
lms886 回答:如何通过API更改用户密码

您的视图绑定到URL模式auth/password-change/(?P<pk>[0-9]+),但您正在请求auth/change-password。该请求应与网址格式匹配。

本文链接:https://www.f2er.com/3166713.html

大家都在问