How to check if request.FILES is empty

5,511 views
Skip to first unread message

Areai51

unread,
Apr 8, 2011, 10:57:12 AM4/8/11
to Django users
Hi,
I have this form which has a couple of form items and a file upload.
Now as long as I select an image to be uploaded the form works fine
and the data is saved, however, when you try to submit the form
without uploading an image I land up getting the error
Exception Type: MultiValueDictKeyError
Exception Value:
"Key 'uploadphoto' not found in <MultiValueDict: {}>"

My code looks something like this

if request.FILES['uploadphoto']:
up = request.FILES['uploadphoto']
upn = up.name
handle_uploaded_file(up)
photo = upn

and in trace back the error is on this line "up =
request.FILES['uploadphoto'] "

How do I write an if statement where I can check if the request.FILES
is not empty then execute the below statements

Thanks for your help in advance
J

Martin Pajuste

unread,
Apr 8, 2011, 11:32:32 AM4/8/11
to django...@googlegroups.com
What you are looking for is probably something like

if 'uploadphoto' in request.FILES:


Martin Pajuste

unread,
Apr 8, 2011, 11:53:44 AM4/8/11
to django...@googlegroups.com
You'll find well written documentation how to treat basic file uploads in Django documentation
http://docs.djangoproject.com/en/dev/topics/http/file-uploads/#basic-file-uploads
Reply all
Reply to author
Forward
0 new messages