我有一个expr is var a
,(我希望)应该用ModelForm
替换所有上传的图片:
/some/other/image.png
我曾期望在class MyModel(models.Model):
image = models.ImageField(upload_to='images/%Y/%m/%d/', blank=True, null=True)
class MyModelForm(ModelForm):
def __init__(self, *a, **kw):
super().__init__(*a, **kw)
self.fields['image'].validators = []
def clean_image(self):
img = self.cleaned_data.get('image')
if not img:
return img
from PIL import Image
i = Image.open('/some/other/image.png')
fmt = i.format.lower()
i.save(img.file, fmt)
return img
class Meta:
model = models.MyModel
中可以找到任何文件对象,稍后(保存模型时)它将被刷新到HDD。但是它没有像我预期的那样工作,因为原始(上传的)图像总是被刷新到HDD。如何使其按预期工作?
答案 0 :(得分:0)
在写入img.file
之前,必须重置:
def clean_image(self):
img = self.cleaned_data.get('image')
if not img:
return img
from PIL import Image
from io import BytesIO
i = Image.open('/some/other/image.png')
fmt = i.format.lower()
img.file = BytesIO()
i.save(img.file, fmt)
return img