Reputation: 23159
Say I have a model and form that support file uploads:
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()
When POSTing from the actual browser form.is_valid()
returns True
, so we can call save()
When I go to use FooForm
to take a PIL
Image
(specifically a <PIL.Image._ImageCrop image mode=RGB size=656x677 at 0x10F6812D8>
), is_valid()
is False
because form.errors
says:
load a valid image. The file you uploaded was either not an image or a corrupted image.
Here's what I'm trying to do to save the form:
img = ... our PIL image ...
post = {'name': name}
file = {'file': img}
form = FooForm(post, file)
if form.is_valid():
form.save()
See what I'm doing wrong that's causing is_valid()
to be False
?
Edit: I think this issue is more about coercing PIL
Image
to something BaseForm
's files
parameter accepts.
Upvotes: 1
Views: 732
Reputation: 23159
This ended up being my solution to get the FooForm
to properly validate. I'm sure there's a better method.
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()
Upvotes: 1
Reputation: 2882
I would recommend changing the form initialisation to use a simple dictionary like this:
img = ... our PIL image ...
form = FooForm({'name': name, 'file': img})
if form.is_valid():
form.save()
Upvotes: 0