[英]Django DRF image field does not accept null values
Django DRF image field does not accept null values. Django DRF 图像字段不接受 null 值。
My model consists of image = models.ImageField(upload_to='uploads/', blank=True, null=True)
我的 model 由
image = models.ImageField(upload_to='uploads/', blank=True, null=True)
组成
If I upload a file there's no problem.如果我上传文件没有问题。 But, if I leave it blank it gives the following error:
但是,如果我将其留空,则会出现以下错误:
The submitted data was not a file. Check the encoding type on the form.
I want to make the image field optional So I set null=True
and blank=True
.我想让图像字段可选所以我设置
null=True
和blank=True
。 But this does not seem to work.但这似乎不起作用。
In DRF your model passes through serializer add this to your serializer:在 DRF 中,您的 model 通过序列化程序将其添加到您的序列化程序:
class ImagePostSerializer(serializers.ModelSerializer):
image = serializers.ImageField(required=False)
class Meta:
model = models.ImagePost
I got the solution.我得到了解决方案。 I was using a different serializer to create an instance of that model.
我使用不同的序列化程序来创建 model 的实例。 I removed the serializer and now it is working.
我删除了序列化程序,现在它正在工作。
Use the DRF Imagefield in serializer在序列化程序中使用 DRF Imagefield
serializers.ImageField(required=False)
DRF ImageField is validating the uploaded file content as matching a known image format. DRF ImageField 正在验证上传的文件内容是否匹配已知的图像格式。 Corresponds to
django.forms.fields.ImageField
对应于
django.forms.fields.ImageField
ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)
Refer: https://www.django-rest-framework.org/api-guide/fields/#imagefield参考: https://www.django-rest-framework.org/api-guide/fields/#imagefield
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.