Multiple File Uploads in Django
As part of yet-to-be-announced project, I’m working with Django. After only a couple days, I’ve been able to produce some pretty cool results. One of the requirements that I have is that a user be able to upload a bunch of files when editing a form. Using Django’s newforms package, I was able to quickly add the ability to upload 1 file, but I wanted the user to be able to upload as many as they wanted.
The solution I came up with was a custom widget (MultiFileInput) and field (MultiFileField) that allows the developer to specify the number of file input boxes to initially show. Also, if desired, the user can be given the option to add (using Javascript) additional file input boxes. All the uploaded files are then validated and returned as UploadedFile objects, just like the FileField included with Django.
The MultiFile widget and field are available, as are some tests that should explain it’s usage. All of the code is in the Public Domain. If you have any questions or know a better way to do it, please leave a comment!
Mogga Said,
November 30, 2007 @ 11:09 am
This looks great… what’s the suggested way to implement this in the model? Can you add custom upload_to for this as well? wow!
Mogga Said,
November 30, 2007 @ 12:20 pm
what’s the name of the key this returns? I’m getting MultiValueDictKeyError
scompt Said,
December 8, 2007 @ 4:45 am
Mogga, this is all at the newforms level, so you’ll probably use it from your view functions. After displaying the form, you’ll have access to the files as UploadedFiles as described here. Then, you can save them where you want.