Django File Upload Gotcha

by Jeremy Jones

In Django, you can specify an image as a database "column" type. Since it's a data type where you define your database model, you would think that the image is in fact stored in your database, but you would be wrong. The only value that is stored in the database is a reference to the file. This is another example of the integration between Django's database and automatic form creation. Here is the "column" I defined for the photo I wanted to upload:

photo = meta.ImageField(upload_to='photos/%Y-%m/', blank=True, null=True)

I was using a standard AddManipulator to process the form that this photo is part of. Every time I tried to upload a file, it only stored the data from the other form fields, but didn't store a reference to the file, nor did it save the file itself. I thought it was odd that I was only saving the request.POST data in my view, but I thought that maybe it should be doing some magic under the covers to get the request.FILES data as well. I found a post on Google Groups thath mentioned that to get file uploads to work you have to update your request.POST dictionary (which it's standard to copy that dictionary to another dictionary) with your request.FILES dictionary. Once I included this missing step, I was able to upload files.

This is one of two non-wife, non-job projects that I'm currently working on. Since it's non-job and non-family, I'm only able, and willing respectively, to devote the wee morning and late night hours to working on it. In a couple of days of my scrap time, I've been able to get the functionality pretty much done. I guess I should be saying "Django rocks" at this point, but I think that's obvious enough that I don't have to say it.