Django表单将PIL图像验证为ImageField
假设我有一个支持文件上传的模型和表单:Django表单将PIL图像验证为ImageField,django,django-forms,python-imaging-library,Django,Django Forms,Python Imaging Library,假设我有一个支持文件上传的模型和表单: 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['fi
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\u valid()
返回True
,因此我们可以调用save()
当我使用FooForm
拍摄PIL
图像
(特别是
)时,是有效的()
是假的
,因为表单错误
说明:
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()
看看我做错了什么,导致是有效的()
是错误的
Edit:我认为这个问题更多的是关于将
PIL
Image
强制到BaseForm
的文件中 我建议将表单初始化更改为使用以下简单词典:
img = ... our PIL image ...
form = FooForm({'name': name, 'file': img})
if form.is_valid():
form.save()
这最终成为我的解决方案,让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()
为什么您要在这里麻烦地使用表单,而不是直接创建Foo对象?FooForm
通过读取其他form.cleaned\u数据来确定保存Foo
的额外数据。把这个文件上传到系统的API。我认为问题在于PIL Image
对于保存到FileField
无效。不确定转换过程是什么。好问题。这只是返回表单。错误:u'此字段(文件)是必需的。
。BaseForm的参数依次为数据(POST),然后是文件(文件)。我认为问题更多的是将PIL
图像转换为表单
考虑上传的文件。