Mission
Mission

Reputation: 1297

POST.getlist() processing

I'm having problems with processing custom form data...

<input type="text" name="client[]" value="client1" />
<input type="text" name="address[]" value="address1" />
<input type="text" name="post[]" value="post1" />
...
<input type="text" name="client[]" value="clientn" />
<input type="text" name="address[]" value="addressn" />
<input type="text" name="post[]" value="postn" />

... (this repeats a couple of times...)

If I do

request.POST.getlist('client[]')
request.POST.getlist('address[]')
request.POST.getlist('post[]')

I get

{u'client:[client1,client2,clientn,...]}
{u'address:[address1,address2,addressn,...]}
{u'post:[post1,post2,postn,...]}

But I need something like this

{
    {0:{client1,address1,post1}}
    {1:{client2,address2,post2}}
    {2:{client3,address3,post3}}
    ...
}

So that I can save this data to the model. This is probably pretty basic but I'm having problems with it.

Thank you!

Upvotes: 0

Views: 1776

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599788

Firstly, please drop the [] in the field names. That's a PHP-ism that has no place in Django.

Secondly, if you want related items grouped together, you'll need to change your form. You need to give each field a separate name:

<input type="text" name="client_1" value="client1" />
<input type="text" name="address_1" value="address1" />
<input type="text" name="post_1" value="post1" />
...
<input type="text" name="client_n" value="clientn" />
<input type="text" name="address_n" value="addressn" />
<input type="text" name="post_n" value="postn" />

Now request.POST will contain a separate entry for each field, and you can iterate through:

for i in range(1, n+1):
    client = request.POST['client_%s' % i]
    address = request.POST['address_%s' % i]
    post = request.POST['post_%s' % i]
    ... do something with these values ...

Now at this point, you probably want to look at model formsets, which can generate exactly this set of forms and create the relevant objects from the POST.

Upvotes: 1

Related Questions