django rest framework ImageField中的自定义验证错误消息
我试图在django rest框架中创建自定义验证错误消息 我有一个productSerializer,如下代码所示:django rest framework ImageField中的自定义验证错误消息,django,django-rest-framework,postman,Django,Django Rest Framework,Postman,我试图在django rest框架中创建自定义验证错误消息 我有一个productSerializer,如下代码所示: class ProductSerializer(serializers.ModelSerializer): # validation name = serializers.CharField(error_messages={'blank': 'Please fillout the product name!'}) price = serializer
class ProductSerializer(serializers.ModelSerializer):
# validation
name = serializers.CharField(error_messages={'blank': 'Please fillout the product name!'})
price = serializers.FloatField(error_messages={'blank': 'Please fillout the product price!'})
slug = serializers.SlugField(error_messages={'blank': 'Please fillout the product slug!'})
size = serializers.CharField(error_messages={'blank': 'Please fillout the product size!'})
description = serializers.CharField(error_messages={'blank': 'Please fillout the description!'})
image = serializers.ImageField(error_messages={'blank': 'Please upload a photo image!'})
# validation
category = serializers.StringRelatedField(read_only=False)
productType = serializers.StringRelatedField()
user = serializers.StringRelatedField()
class Meta:
model = Product
fields = "__all__"
我的观点应该是:
class ProductsList(APIView):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
def post(self, request):
serializer = ProductSerializer(data=request.data)
category = Category.objects.get(name=request.data['category'])
productType = ProductType.objects.get(name=request.data['productType'])
if serializer.is_valid():
serializer.save(category=category, productType=productType)
return Response("SUCCESS!!!!!!", status=200)
else:
return Response(serializer.errors, status=400)
问题:
我希望图像字段错误消息是我写的,当它为空时。
但我总是面对“没有提交任何文件”的信息
问题:
如何验证图像字段是否为空?您可以执行以下操作:
class Meta:
model = Product
extra_kwargs = {
"image": {
"error_messages": {
"required": "Please upload a photo image"
}
}
}
您可以添加到序列化程序中,以使用自定义消息引发ValidationError
您可以通过以下方式修改序列化程序:
class ProductSerializer(serializers.ModelSerializer):
# validation
name = serializers.CharField(error_messages={'blank': 'Please fillout the product name!'})
price = serializers.FloatField(error_messages={'blank': 'Please fillout the product price!'})
slug = serializers.SlugField(error_messages={'blank': 'Please fillout the product slug!'})
size = serializers.CharField(error_messages={'blank': 'Please fillout the product size!'})
description = serializers.CharField(error_messages={'blank': 'Please fillout the description!'})
image = serializers.ImageField(required=False, error_messages={'blank': 'Please upload a photo image!'})
# validation
category = serializers.StringRelatedField(read_only=False)
productType = serializers.StringRelatedField()
user = serializers.StringRelatedField()
def validate(self, data):
if "image" not in data:
raise serializers.ValidationError("Please upload a photo image!")
return data
class Meta:
model = Product
fields = "__all__"
编辑:您可能还需要为ImageField设置required=False,以便序列化程序不会在.validate()方法之前提示缺少字段(因为在所有serializer.field中默认情况下required为True)
您也可以进行测试,但我担心在调用自定义字段级验证方法之前,会引发此字段丢失的事实。简单地说,在序列化程序类中添加此
def validate
方法-
def validate_image(self, image):
image = image.strip()
# this will check if the image is blank. If it is then it will raise a
# validation error.
if not image:
raise serializers.ValidationError("Please upload a photo image!")
return image
当图像为空白时,当前的行为是什么?@JPG它给了我“{”图像的响应:[“没有提交任何文件。”]}“我尝试了,但没有积极的结果。我写的代码与您的答案完全相同,但方式不同。每当字段为空时,我需要捕捉错误,这意味着“空白”。感谢您的帮助,不幸的是,这对我没有帮助。我需要验证空白图像字段。图像字段(空白或已填充)总是从客户端发送到服务器,因此应用程序中没有必需的错误。能否指定“空白图像”的含义?它是空的还是客户端根本没有发送此字段时为空的?我看到ImageField有'allow_empty_file'参数,默认情况下为False。也许您可以将其更改为True,以便序列化程序将数据传递给自定义的.validate()方法进行进一步验证,而不是引发“未提交任何文件”。然后在.validate()中,您可以检查“image”是否在数据中,以及“image”是否为None。我的意思是,当图像字段从客户端发送时,但是用户没有在其中放入任何图像,因此该字段为空。我还在序列化程序上尝试了
allow\u empty\u file=True
,但没有任何更改required=False
也不会更改任何内容。