Jamie
Jamie

Reputation: 31

Why does this Django form complain "this field is required" for an image field?

Using 'Photologue', I can upload images as part of a form no problem. In the test plans however, I am having trouble getting an image to validate.

In tests.py:

data_photo = {'competition': self.newcomp,  
                  'title': 'Rabbit',
                  'image': open('photocompetitions/static/img/body_bg.jpg'),
                  'flickr_id': '425258',
                  'description': 'A picture of a rabbit',
                  'location': 'POINT (5000 5000)',
                  'location_description': 'Just some random place',
                  'copyright': 'Copyright 2011'}
photoform = PhotoForm(data_photo)

Everything works fine except the 'image' field which fails as a 'This field is required.' message so I am assuming that it is not being received despite the open() command. the 'image' field is the photologue's ImageModel model and appears on the site as a standard upload form.

Upvotes: 3

Views: 2207

Answers (3)

Sergey Lyapustin
Sergey Lyapustin

Reputation: 1937

You need to use 'rb' options for open file:

'image': open('photocompetitions/static/img/body_bg.jpg', 'rb')

Upvotes: 2

Ivan Virabyan
Ivan Virabyan

Reputation: 1686

You have to pass an image not in data, but in the files parameter of the form.

from django.core.files.uploadedfile import SimpleUploadedFile

img = open('photocompetitions/static/img/body_bg.jpg')
uploaded = SimpleUploadedFile(img.name, img.read())
photoform = PhotoForm(data_photo, files={'image': uploaded})

Upvotes: 6

luc
luc

Reputation: 43096

Did you try to use a bmp rather than a jpg?

I remember that there is an issue with the way PIL is loaded by the django test framework.

the jpg format may not be enabled correctly in this case but bmp should be ok.

I hope it helps

Upvotes: 0

Related Questions