我有这个序列化器:
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函数的函数更新之外,但是我不知道如何
答案 0 :(得分:1)
您可以为当前密码编写自定义验证器
def validate_current(self, value):
if not self.instance.check_password(value):
raise serializers.ValidationError("Current password is not correct")
return value
您将不得不从序列化程序的视图中传递实例