简体   繁体   中英

How to change a password for a User from API

I need to prepare an endpoint in DRF which will allow to change a Users password. So I read this post: How to update user password in Django Rest Framework?

But, to be honest even after read that article and implemented code from that article in my App It still doesn't work. Im a newbie in Django and Python and I dont understant what I do wrong. Can you help me in understanding what I do wrong?

Here below is the code I implemented:

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

So now I send the PUT on http://localhost:8000/auth/change-password/ with following body:

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

and I get this message:

<h1>Not Found</h1>
<p>The requested resource was not found on this server.</p>

Your view is tied to the URL pattern auth/password-change/(?P<pk>[0-9]+) yet you are requesting auth/change-password . The request should match the URL pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM