upload field of an invalid form points to nowhere

This may be a question with a very simple answer, however I couldn't come across to one on the internet.

I am writing a Django application. I have a form with an unrequired ImageField. After the user has submitted the form (with an image), if the form is invalid, on the serverside I populate the form with the request data and files (eg: form = FooForm(request.DATA, request.FILES, instance = foo)and send the response back to the client.

On the client the other fields are displayed OK, but the image field doesn't point to anywhere. As the image field is not required, the user usually overlooks the situation and resubmits the form without the image.

I am lost on even whether this is an issue or this is how it is expected to work anyway. If this is an issue please state so that I provide more details.

13.10.2009 18:55:44
1 ОТВЕТ
РЕШЕНИЕ

This is an unavoidable result of the way browser security works. It's not possible for any server-side system to set the initial value of a file upload field, as it does for any other input field. This is to stop malicious sites uploading content from your computer without your permission - otherwise, a site could set the field to default to your password file, for example.

Obviously, this is is a problem if you actually want the file the user uploaded - if the form was initially invalid, it won't have been saved, and the second time through the file will be lost unless the user uploads it again. One possible solution might be to put the file upload on its own form as a second page - once the form has been validated and saved, the second form is displayed which only has the file on it. The Trac bugtracker works like this, by having a checkbox on the main form for 'I have a file to upload', and taking the user to that form if the checkbox is selected.

1
13.10.2009 19:13:38
Thanks, Daniel. I didn't think of sending the file back to the client, however I thought -just as it is done with the other fields- maybe the path string could be send and restored.
shanyu 13.10.2009 21:24:39
+1 - Another thing you could do would be to add a hidden field called something like "suspectIntendedFileUpload", which you could set on receipt of a submission with a file upload. If you then get a further submission with that hidden field set, and no file upload, you could unset the field and warn the user.
Dominic Rodger 14.10.2009 05:52:39