Reputation: 45114
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.
Upvotes: 3
Views: 2865
Reputation: 823
QueryDict
's getlist
is what you're looking for.
From the docs:
>>> q = QueryDict('a=1', mutable=True)
>>> q.update({'a': '2'})
>>> q.getlist('a')
['1', '2']
Upvotes: 0
Reputation: 10585
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.
Upvotes: 0
Reputation: 54089
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.
Upvotes: 2
Reputation:
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
Upvotes: 2
Reputation: 179139
You should read about QueryDict objects:
>>> q = QueryDict('a=1&a=2&a=3')
>>> q.lists()
[('a', ['1', '2', '3'])]
Upvotes: 5