Here is the problem, I have a Django Form containing a File field, namely:
photo = forms.FileField(help_text="Please attach a photo", required=False)
If the form validates, the File field is bounded and saved correctly. The problem is when the user fills all the form and it doesn't validate: the path of the selected file disappear.
So, if the user doesn't realize about this, he/she fix the other fields errors and submit again - with no photo this time.
Just in case, the form is created in the view like this:
ProfileForm(request.POST or None, request.FILES or None)
and the HTML is:
<div id="uniform-id_photo" class="uploader">
<input id="id_photo" class="clearablefileinput" type="file" name="photo" size="19" style="opacity: 0;">
<span class="filename" style="-moz-user-select: none;">No file selected</span>
<span class="action" style="-moz-user-select: none;">Choose File</span>
</div>
Has anyone had the same problem before? Any thoughts towards a solution? :)
Thanks!
Unfortunately, this is a problem (really a security feature) imposed by browsers, and is not solvable, as such. Browsers will not let you specify an initial value for file inputs, and there's nothing that you will be able to do to work around that.
The reason is that if a website could do this, it would open up a vector that would allow any website to steal any file on your computer by guessing file paths--they could just have a script running in the background that tried to post interesting files back to the server.
The only workaround is to actually save the uploaded file on the server regardless of whether the form validates, and then when you render the form and errors back to the user, indicate that you have received a file and that they should only fill out that field to replace it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With