简体   繁体   中英

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

views.py

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

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

serializers.py

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

        extra_kwargs = {
            'password' : {
                'write_only':True,
                '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

urls.py

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


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

permissions.py

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

在此处输入图片说明

Response :

在此处输入图片说明

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']
        instance.set_password(validated_data['password'])
        instance.save()

        return instance

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