views:

941

answers:

3

I'm not sure if I'm just form building impaired or not thinking about this the right way. I'm attempting to build a form similar to Gmail's 'compose' form that has an AJAX image uploader. I have a portion of code that uploads the image and returns an image ID working fine. Once I receive the image ID back I've tried appending it to my form in a hidden checkbox field. I want to allow users to upload multiple images, and I'd also like to keep all my hidden checkboxes the same name so I can easily iterate over the values. Essentially this:

Client side (this is from Gmail but on mine these will be hidden):

<input type="checkbox" checked="" value="125e6e5e7d8a2601_125e6e5e7d8a2601_0.2_-1" name="attach" id=":4s"/>
<input type="checkbox" checked="" value="125e6e5e7d8a2601_125e6e5e7d8a2601_0.1_-1" name="attach" id=":50"/>

Server side:

       for picture_id in request.POST["attach"]:
            #do stuff here with the picture_id

Unfortunately I only receive one of the picture_ids and request.POST["attach"] iterates over it like a string. I'm not sure how to resolve my issue and send all the image IDs without using something like a form <select> where multiple items can be selected because I'd have to manually add items and select them.

Hopefully this explanation is clear, I'm sure I'm just missing something trivial. Thanks for the help in advance!

+11  A: 

If you're expecting a list for the key attach, you should use request.POST.getlist('attach'). Doing request.POST['attach'] will only give you the last value, which is a string.

Happy new year!

elo80ka
+1: I just learned something new about POST! Thanx!
Peter Rowell
Thanks a lot, this is exactly what I was looking for! :)
Jordan Messina
A: 

take a look at the django docs for forms fields:

http://docs.djangoproject.com/en/dev/ref/forms/fields

Etienne
A: 

Once again I'll point to my old friend the jQuery taconite plugin. If you are using AJAX to push the image to the server, try returning a taconite response which makes multiple changes (sticks the ID in one place, appends a hidden input someplace else, etc.) to your DOM. It can also run JS to do some other things within the page's environment. Very, very handy.

As far as your using the same name for multiple input fields, I'm not sure it works the way you would like. Using the Live HTTP Headers plugin for Firefox I can see foo=1&foo=2&foo=3&foo=4&foo=5&foo=6 being passed but both PHP and Django only deliver the last value, not an array. You might try creating names like "attach_1", "attach_2", etc. and just loop through your POST values and suck them out that way. Either that or get the raw POST data and parse it yourself.

See elo80ka's answer for how to do this. (Ya learn sometin' new every day!)

Peter Rowell