I want to ask that following code provides updating password but I want to update password after current password confirmation process. So what should I add for it? Thank you.
class UserPasswordSerializer(ModelSerializer):class Meta:model = Userfields = ['password']extra_kwargs = {"password": {"write_only": True},}def update(self, instance, validated_data):for attr, value in validated_data.items():if attr == 'password':instance.set_password(value)else:setattr(instance, attr, value)instance.save()return instance
I believe that using a modelserializer might be an overkill. This simple serializer & view should work.
Serializers.py
from rest_framework import serializers
from django.contrib.auth.models import Userclass ChangePasswordSerializer(serializers.Serializer):model = User"""Serializer for password change endpoint."""old_password = serializers.CharField(required=True)new_password = serializers.CharField(required=True)
Views.py
from rest_framework import status
from rest_framework import generics
from rest_framework.response import Response
from django.contrib.auth.models import User
from . import serializers
from rest_framework.permissions import IsAuthenticated class ChangePasswordView(UpdateAPIView):"""An endpoint for changing password."""serializer_class = ChangePasswordSerializermodel = Userpermission_classes = (IsAuthenticated,)def get_object(self, queryset=None):obj = self.request.userreturn objdef update(self, request, *args, **kwargs):self.object = self.get_object()serializer = self.get_serializer(data=request.data)if serializer.is_valid():# Check old passwordif 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 getself.object.set_password(serializer.data.get("new_password"))self.object.save()response = {'status': 'success','code': status.HTTP_200_OK,'message': 'Password updated successfully','data': []}return Response(response)return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)