How to update user password in Django Rest Framework

0 votes

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?

class UserPasswordSerializer(ModelSerializer):

    class Meta:
        model = User
        fields = [
            '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
Jul 1, 2020 in Python by kartik
• 37,520 points
9,238 views

1 answer to this question.

0 votes

Hello @kartik,

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 User

class 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 = 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()
                response = {
                    'status': 'success',
                    'code': status.HTTP_200_OK,
                    'message': 'Password updated successfully',
                    'data': []
                }

Hope this works!!

Thank You!!

answered Jul 1, 2020 by Niroj
• 82,840 points

Related Questions In Python

0 votes
1 answer

How to return custom JSON in Django REST Framework?

Hello @kartik, There are 2 ways to custom ...READ MORE

answered Jun 25, 2020 in Python by Niroj
• 82,840 points
11,161 views
0 votes
1 answer

How to add annotate data in django-rest-framework queryset responses?

Hello @kartik, The queryset returned from get_queryset provides ...READ MORE

answered Jun 25, 2020 in Python by Niroj
• 82,840 points
6,125 views
0 votes
1 answer

How to secure APIs for Registration and Login in Django Rest Framework?

Hello @kartik, you cannot have an authentication system ...READ MORE

answered Jun 25, 2020 in Python by Niroj
• 82,840 points
2,878 views
0 votes
1 answer

How to disable a method in a ViewSet, django-rest-framework

Hello @kartik, You could keep using viewsets.ModelViewSet and define http_method_names on your ...READ MORE

answered Jun 26, 2020 in Python by Niroj
• 82,840 points
10,849 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
2,449 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
1,564 views
0 votes
1 answer

How to get Request.User in Django-Rest-Framework serializer?

Hello @kartik, You cannot access the request.user directly. You need ...READ MORE

answered Aug 12, 2020 in Python by Niroj
• 82,840 points
13,697 views
0 votes
1 answer

How to return the current user with Django Rest Framework?

Hello @kartik, The best way is to use ...READ MORE

answered Jun 25, 2020 in Python by Niroj
• 82,840 points
12,034 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP