Search code examples
django-rest-frameworkdjango-serializer

Django rest-framework - set_password on instance in update function returns 'None'


I'm trying to update the password of a django user with the ModelSerializer of the django rest-framework. Using set_password inside the create method works without any problem. But whenever I call set_password on the instance within the update mehod, it returns 'None' .

class CustomUserSerializer(serializers.ModelSerializer):

    def create(self, validated_data):
        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user

    def update(self, instance, validated_data):
        
        if validated_data.get('password'):
            instance.password = instance.set_password(validated_data['password'])
        instance.save()
        return instance

Even setting a static password returns 'None':

def update(self, instance, validated_data):
    instance.password = instance.set_password('secret')
    instance.save()
    return instance

But I have no glue, why this happens. Django version is 4.1.2, djangorestframework 3.14.0


Solution

  • As it clearly states in the docs that user.set_password takes care of hashing the password and setting it on user instance, it just does not save the instance in the database. so instead of

    instance.password = instance.set_password('secret')
    instance.save()
    

    you should be doing

    instance.set_password('secret')
    instance.save()
    

    similar to what you did in def create(self, validated_data)