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

标签 python django image rest django-rest-framework

我以为我的问题是 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/

相关文章:

Python:保存动态创建的对象类型

ruby-on-rails - 我的应用找不到我的图片路径

javascript - 从 Javascript 中的 HTTP Post 请求返回图像

python - 无法使用pypyodbc在python中使用where子句运行mssql select查询

python - 有什么方法可以像 django makemessage 一样生成 Tornado 本地化 CSV 文件吗?

python - 使用 matplotlib 在 python 中的 xkcd 注释中不会中断行

django - 初始部署后,在生产环境中运行 djangosyncdb 是否安全?

django - 部署的 Django 项目不加载静态文件

python - mypy 错误 - 尽管使用了 'Union',但类型不兼容

objective-c - NSImage 行为怪异