假设我有一个支持文件上传的模型和表单:
class Foo(Document):
name = StringField()
file = FileField()
class FooForm(Form):
name = CharField()
file = ImageField()
def save(self):
Foo(name=self.cleaned_data['name'], file=self.cleaned_data['file']).save()
当从实际浏览器form.is_valid()
发帖时返回True
,我们可以致电save()
当我使用FooForm
来获取PIL
Image
(特别是<PIL.Image._ImageCrop image mode=RGB size=656x677 at 0x10F6812D8>
)时,is_valid()
为False
,因为{{ 1}}说:
form.errors
以下是我要保存表单的方法:
load a valid image. The file you uploaded was either not an image or a corrupted image.
看看我做错了导致img = ... our PIL image ...
post = {'name': name}
file = {'file': img}
form = FooForm(post, file)
if form.is_valid():
form.save()
成为is_valid()
?
修改:我认为此问题更多的是将False
PIL
强制转换为Image
BaseForm
参数接受的内容。
答案 0 :(得分:1)
最终成为我的解决方案,让FooForm
正确验证。我确信有更好的方法。
img = ... our PIL image ...
buffer = StringIO()
img.save(buffer, 'png')
buffer.seek(0)
image_file = SimpleUploadedFile('foo.png', buffer.read(), content_type="image/png")
buffer.close()
post = {'name': name}
file = {'file': image_file}
form = FooForm(post, file)
if form.is_valid():
form.save()
答案 1 :(得分:0)
我建议更改表单初始化以使用这样的简单字典:
img = ... our PIL image ...
form = FooForm({'name': name, 'file': img})
if form.is_valid():
form.save()