Reputation: 4885
So I have a settings page, and the user can upload a photo to the website with a post request from a form, but right now, I can't detect if the user uploaded a photo or not, since there are also other parts of the form, with one submit button at the bottom. Right now, I'm using if 'file_input' in request.POST:
, but it always returns true, even though the user didn't upload a photo. How can I detect if the user actually uploaded a photo. The html is:
<form class="group-photo" action="/${groupName}/settings" method="post" style="vertical-align:text-bottom" enctype="multipart/form-data">
<span style="font-size:17px;font-weight:bold;">Group Photo</span>
<img style="border-radius:15px;margin-top:5px;margin-bottom:5px;" src="/static/group/${photo_id}_120.${photo_ext}">
<br>
<div class="fileinputs">
<input class="file" type="file" name="file_input" value="Choose image">
<div class="fakefile" style="margin-left:40px;">
<input type="button" class="btn btn-primary" value="Choose image"/>
</div>
</div>
<br/>
<span style="font-size:17px;font-weight:bold;">Description</span>
<textarea class="groupbio" name="groupbio">${bio}</textarea>
<br>
<br>
<p><input class="btn btn-success" type="submit" name="submitted" value="Save Changes"></p>
</form>
Upvotes: 1
Views: 812
Reputation: 1124758
The browser includes all file input elements in the form, even when empty, so the 'file_input' in request.POST'
test will always be True, but if empty, it's an empty unicode string (u''
).
A proper file upload has a filename, test for that:
if 'file_input' in request.POST and hasattr(request.POST['file_input'], 'filename'):
File uploads are cgi.FieldStorage
instances, and the filename
test is what the cgi
module documentation recommends:
If a field represents an uploaded file, accessing the value via the value attribute or the getvalue() method reads the entire file in memory as a string. This may not be what you want. You can test for an uploaded file by testing either the filename attribute or the file attribute.
Upvotes: 6