gpt4 book ai didi

python - 如何使用 Django Rest Framework 清除图像?

转载 作者:太空狗 更新时间:2023-10-29 21:51:52 24 4
gpt4 key购买 nike

我以为我的问题是 https://github.com/encode/django-rest-framework/issues/937应该由 https://github.com/encode/django-rest-framework/pull/1003 修复但看起来,无论我发送 None 还是空字符串,DRF 都不满意。

我正在使用 Django 1.11.6 和 DRF 3.7.7

class Part(models.Model):
image = models.ImageField(null=True, blank=True)

class PartSerializer(serializers.ModelSerializer):
class Meta:
model = Part
fields = ('id', 'image')

class PartDetail(generics.RetrieveUpdateAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
parser_classes = (MultiPartParser, FormParser)

# put image, works fine
with tempfile.NamedTemporaryFile(suffix='.jpg') as fp:
image = Image.new('RGB', (100, 200))
image.save(fp)
fp.seek(0)
data = {'image': fp}
self.client.put('/path/to/endpoint', data, format='multipart')

# clear image, attempt #1
data = {'image': None}
self.client.put('/path/to/endpoint', data, format='multipart')
AssertionError: {'image': ['The submitted data was not a file. Check the encoding type on the form.']}

# clear image, attempt #2
data = {'image': ''}
self.client.put('/path/to/endpoint', data, format='multipart')
AssertionError: <ImageFieldFile: None> is not None

最佳答案

您必须明确指定图像字段以允许它为空。

使用这个:

class PartSerializer(serializers.ModelSerializer):
image = serializers.ImageField(max_length=None, allow_empty_file=True, allow_null=True, required=False)

class Meta:
model = Part
fields = ('id', 'image')

检查 docs了解更多详情。

关于python - 如何使用 Django Rest Framework 清除图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48676365/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com