Can't change user password for Django user model using ModelViewSet

I was using Django user model using the ModelViewSet. When I am making a request to update the password for the current user that is logged in. Although I get a 200 OK response but my password never changes to the new one that I changed.

I also tried making the request from my admin user and when I made the PUT request with the password, it got changed to something else and I was logged out from the django admin panel.

Here is my

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    permission_classes = [IsAuthenticated, IsOwnerOfObject]
    authentication_classes = (TokenAuthentication,)

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'password']

        extra_kwargs = {
            'password' : {
                'required': True
    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        Token.objects.create(user=user) # create token for the user
        return user

router = DefaultRouter()
router.register('articles', ArticleViewSet, basename='articles')
router.register('users', UserViewSet, basename = 'users')

urlpatterns = [
    path('api/', include(router.urls)),

class IsOwnerOfObject(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        return obj == request.user

Here is how I am making the request, with Authorisation token in the Headers field

enter image description here

Response :

enter image description here

Answers: 1

Answered by Jose Antonio Castro Castro, Oct. 22, 2021, 9:26 a.m.

As @BrianDestura says, you need call set_password to correctly update it.

class UserSerializer(serializers.ModelSerializer):

    # --> Add this method
    def update(self, instance, validated_data):
        # We Can change the username?
        instance.username = validated_data['username']

        return instance