how to use check_password inside validate function

2019-08-17 05:10发布

问题:

I have this serializer:

class ChangePasswordSerializer(DynamicFieldsModelSerializer):
    current = serializers.CharField()
    confirm = serializers.CharField()

   class Meta:
        model = models.User
        fields = ('password', 'current', 'confirm')
        validators = []

    def update(self, instance, validated_data):
        if instance.check_password(validated_data.get('current')):
            instance.set_password(validated_data['password'])
            instance.save()
        else:
            raise serializers.ValidationError("Current password is not correct")
        return instance

I have this inside my update function:

instance.check_password(validated_data.get('current'))

but I want this action happens outside of function update in validate_current function, but I dont know how

回答1:

You can write custom validator for the current password

def validate_current(self, value):
     if not self.instance.check_password(value):
        raise serializers.ValidationError("Current password is not correct")
     return value

you will have to pass instance from view in serializer