如何在validate函数中使用check_password?

时间:2019-05-08 11:30:37

标签: django-rest-framework

我有这个序列化器:

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

我的更新函数中包含以下内容:

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

但是我希望此操作发生在validate_current函数的函数更新之外,但是我不知道如何

1 个答案:

答案 0 :(得分:1)

您可以为当前密码编写自定义验证器

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

您将不得不从序列化程序的视图中传递实例