views:

142

answers:

4

Hi,

I want to submit a form (by POST) that will submit N (unknown) user_id's. Can I make a view receive those ids as a list?

For example

def getids(request,list):

   for id in list:
       usr = User.objects.get(pk=id);
       //do something with it.
       usr.save()

Is

for id in request.POST['id']:

even possible?

I'm looking for the best accepted way.

+5  A: 

You should read about QueryDict objects:

>>> q = QueryDict('a=1&a=2&a=3')
>>> q.lists()
[('a', ['1', '2', '3'])]
Ionuț G. Stan
Will do, thanks
Tom
+2  A: 

Very close. The POST parameters are actually contained in a QueryDict object in the request.

def getids(request):
    if request.method == 'POST':
        for field in HttpRequest.POST:
            // Logic here
cpharmston
Thanks! I'll take a look at it.
Tom
+2  A: 

If you are submitting lots of identical forms in one page you might find Formsets to be the thing you want.

You can then make one Form for the userid and then repeat it in a Formset. You can then iterate over the formset to read the results.

Nick Craig-Wood
Yes, i considered that approach, but as a newbie with a deadline i declined it. Will probably use formsets in the future. Thanks !
Tom
A: 

You can create the form fields with some prefix you could filter later.

Say you use form fields with names like uid-1, uid-2, ... uid-n

Then, when you process the POST you can do:

uids = [POST[x] for x in POST.keys() if x[:3] == 'uid']

That would give you the values of the fields in the POST which start with 'uid' in a list.

Facundo
That should be x[:3], not x[:2]
Ian Clelland
yeap, sorry, my bad
Facundo