开发者

Django - HTTP Uploading of Multiple Images

I looked at this question:

Uploading multiple files with Django

but it did not seem to help as I have issues regarding it:

  1. I don't want to deal with flash sessions using SWF Uplo开发者_开发技巧ad and Uploadify because I need to do uploads that only authenticated users can do.
  2. newforms are for older versions of django, I am using 1.3

Using Django, how can I have this HTML form structure:

<form enctype="multipart/form-data" action="." method="post">
 <label for="id_image_1">Image 1</label>
 <input type="file" name="image[]" id="id_image_1" />

 <label for="id_image_2">Image 2</label>
 <input type="file" name="image[]" id="id_image_2" />
</form>

and handle it using a view?


If you have a fixed number of filefields, you could simply define a form with enough filefields, or add filefields programatically in a form's constructor. See the Django docs on File Uploads.

If you want some sort of dynamic functionality (a la gmail's "add another file"), then you could define a formset using a form with a single filefield. Display a single form initially and when you want to add another, use a little javascript to produce the new form and update the formset's management form. There are a number of snippets floating around to help you do this, though they may need some tweaking. See the Django docs on File Uploads and Formsets.

Another option may be to use a custom widget and field, though I have not reviewed or tried this.

On the off-chance you aren't aware, the name="image[]" scheme is PHP specific and has no special meaning in other languages, unless you reimplement it.


newforms is what the current forms were called before 1.0. Furthermore, if you got your form validated, http://docs.djangoproject.com/en/dev/topics/http/file-uploads/, you'll have your files as a list (tuple, probably, but sequence anyway) in request.FILES['image'], so just do:

if request.method == 'POST':
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
       for f in request.FILES['image']:
           handle_uploaded_file(f)

You'll have to write handle_uploaded_file yourself, the URL explains how

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜