首页 文章

Django Form将PIL Image验证为ImageField

提问于
浏览
1

假设我有一个支持文件上传的模型和表单:

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()

当我使用 FooFormPIL Image (特别是 <PIL.Image._ImageCrop image mode=RGB size=656x677 at 0x10F6812D8> )时, is_valid()False 因为 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()

看看'm doing wrong that'导致 is_valid()False

Edit: 我认为这个问题更多的是将 PIL Image 强加给 BaseFormfiles 参数接受 .

2 回答

  • 0

    这最终成为我的解决方案,让 FooForm 正确验证 . 我_2832201是一个更好的方法 .

    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

    我建议更改表单初始化以使用这样的简单字典:

    img = ... our PIL image ...
    form = FooForm({'name': name, 'file': img})
    if form.is_valid():
        form.save()
    

相关问题