django - drf : custom field validation function not being called

标签 django serialization django-rest-framework

我有一个以下序列化器:

class QuestionSerializer(serializers.ModelSerializer):
    choices = ChoiceSerializer(many=True)
    image = Base64ImageField(required=False)

    def validate_image(self, value):
        import ipdb
        ipdb.set_trace()
        # if value.get('fileArray', None):
        #     if value.get('dataURL', None):
        #         return value.get('dataURL')
        #     else:
        #         raise serializers.ValidationError("No file data present")
        # else:
        #     return None

    class Meta:
        model = Question
        fields = ('id', 'detail', 'image', 'true_false_answer', 'type', 'choices')

然后在 View 中:

serializer = QuestionSerializer(data=data)
serializer.is_valid()

这给了我错误 和:

serializer.errors

给出:

{'image': ['The submitted data was not a file. Check the encoding type on the form.']}

我发现 validate_image 从未被调用。 可能是什么问题?

最佳答案

What I found is validate_image is never called. What might be the problem?

如果默认 DRF 验证通过,

validate_image 将被调用。

当序列化器已经知道该字段无效时,验证图像字段是没有意义的。

关于django - drf : custom field validation function not being called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43228274/

相关文章:

C++ 序列化 - 使用从 char * 到结构的 reinterpret_cast

python - 如何使用 Django REST 序列化程序对保留键进行验证?

python - Robobrowser 如何使用代理

django - 如何设置表单字段值 - django

python - 对于 django social_auth 中的类型字符 varying(16),DataError 值太长

java - boolean 类型序列化和反序列化单元测试失败

java - 将java对象序列化到文件时是否可以在序列化文件的开头插入一个对象

Python 3 Django Rest Framework - 如何向这个 M-1-M 模型结构添加自定义管理器?

python - 您如何允许使用未经身份验证的请求访问 Django Rest Framework 中的某些 View ?

python - Django 模板语法错误