Downloading Django FileField

Lets say you are using Django’s FileField in one of your models. You can put a link to that file in your templates by using the “url” attribute for the field. If the user clicks on the link, the default is for the browser to try to open the file. The user needs to right click to save the file. What if you want saving the file to be the default.

If you are using HTML 5, you can just add the “download” attribute to your <a> tag.

Django FileField and Invalid Forms

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.