I was writing a form for uploading a CSV file. I had fields to let the user map their columns to my model fields and I had a forms.FileField() to get the filename. I even remembered to include “multipart/form-data” in the form tag.
Because it is likely my users will get confused between their excel files and their CSV files, I added some code in the form clean method to make sure the file is CSV-ish. Then I tested that code by trying to upload some excel file. This code worked as expected and the form was found to be invalid. So far so good.
Like all the rest of the form fields, I expected that when the invalid form was rendered, the name of the file would appear in the file upload form field. This was desirable because it would let the user see what file was invalid. The problem was no matter what I tried, the FileField widget showed “No file chosen”.
It turns out this was not an error, it was a feature. As mentioned here in StackOverflow,
HTML file input fields are never populated with existing data – this is a browser restriction, nothing to do with Django. It’s a security measure, to stop malicious sites tricking you into uploading arbitrary content from your computer.
What to do? Just add the filename to the error message.