I encountered a scenario where I have a list that I needed to pass over in a form, something like:
<input type="hidden" name="ids" value="1,2,3,4,5">
I figured in my views.py, I would just loop over the items (it's a list, right) and process the ids. Instead, Django did something I found very peculiar. When I iterated over the form field:
for id in request.POST['ids']:
print id
printed "1" "," "2" "," etc. Not exactly what I was looking for. Instead of trying to fudge around with this, I found a much better solution where I just had 5 form fields, all named id:
<input type="hidden" name="id" value="1">
<input type="hidden" name="id" value="2">
<input type="hidden" name="id" value="3">
etc.
Then, in my view:
ids = request.POST.getlist('id')
for id in ids:
print id
properly printed "1" "2" "3", etc. I could see how this might be really useful dealing with checkboxes or radio buttons as well.
Share on Twitter
Share on Facebook