【问题标题】:How to change a password for a User from API如何从 API 更改用户的密码
【发布时间】: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


    【解决方案1】:

    您的视图与 URL 模式 auth/password-change/(?P&lt;pk&gt;[0-9]+) 相关联,但您正在请求 auth/change-password。请求应与 URL 模式匹配。

    【讨论】:

    • 是的:-)。我在一分钟前注意到了这一点。抱歉,感谢您的快速回复。现在一切正常
    猜你喜欢
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多