form = AddItemForm(request.POST, request.FILES)
if form.is_valid()
do_stuff
return render_to_response(blah.html, {'form':form})
Now form will have the error information along with the original values of the fields, but it does not retain a selected file How do I keep the selected file if the form fails validation?
Django will only save the file to disk on its own if you are using a modelForm and you successfully save a new instance of that model which has a fileField.
In your case what you have to do is get the file from the request.FILES dictionary, and save it to disk on your own. It should look something like this.
Now that you have the file saved to disk, you just have to remember the path to the file, so you can open it again when the user resubmits the failed form.
Bit tricky but here is the logic.
On first load, hidden field is empty, so nothing happens.
On selection of file, it saves path+name in hidden field.
On second load, hidden field is not empty, so it will set file path
This way, all the dirty work happens in Browser, and Unless you have valid form, you don't have to save the file on server.
The problem with what you want to do is that, for security reasons, browsers will not allow a file input box to have a pre-selected value on page load. This is true even if it is simply preserving the value from a previous instance of the same page. There is nothing Django can do to change this.
If you want to avoid asking the user to re-select and re-upload the file, you will need to save the uploaded file even when validation fails, and then replace the file input field with something to indicate that you already have the data. You would also probably also want a button that runs some JavaScript to re-enable the file field if the user wants to put in a different file. I don't think Django comes with any machinery for this, so you'll have to code it yourself.
Try django-file-resubmit
insallation
settings.py
usage
or
Ok, so I first upvoted and implemented Narendra's solution before realizing it couldn't work as javascript can't set input type="file" values. See: http://www.w3schools.com/jsref/prop_fileupload_value.asp
But here's a solution that works:
Ok, here's a sketch of the procedure, which works for me of an example where you are trying to save a pdf of a book with an email address (chosen as emails sometimes do not validate) of an author.
models.py
forms.py
views.py
bookform_template.html