tags:

views:

139

answers:

7

In PHP you can create form elements with names like:

category[1]
category[2]

or even

category[junk]
category[test]

When the form is posted, category is automatically turned into a nice dictionary like:

category[1] => "the input value", category[2] => "the other input value"

Is there a way to do that in Django? request.POST.getlist isn't quite right, because it simply returns a list, not a dictionary. I need the keys too.

A: 

You can do request.POST['namefromform'] - I take it this isn't what you're looking for?

Ninefingers
I know about that :) The problem is I don't know the key ahead of time. The input elements on the form are dynamically generated.
Matt
for the keys, maybe request.POST.keys() does the trick.
dzen
A: 

Use request.POST.keys()

nosklo
The problem with that is I get _all_ the keys. I just want the keys associated with a group of related form elements (like how PHP does it).
Matt
A: 

Sorry, as far as I've found, getlist is all there is for what you want, but you could easily parse the request using request.POST.keys() and turn them into dictionaries.

UltimateBrent
I'm afraid I might have to do that. Seems like there would be a better way though!
Matt
A: 

I'm not a python expert but you might try

for key,value in request.POST.iteritems() 
  doSomething....
VolkerK
A: 

Check my answer from here: http://stackoverflow.com/questions/1482362/django-can-a-view-receive-a-list-as-parameter/1482365#1482365

Ionuț G. Stan
I don't think that is any different than `request.POST.getlist`. Notice how the PHP input has a name, keys and values?
Matt
A: 

Hardly pretty, but it should get the job done:

import re

def getdict(d, pref):
  r = re.compile(r'^%s\[(.*)\]$' % pref)
  return dict((r.sub(r'\1', k), v) for (k, v) in d.iteritems() if r.match(k))

D = {
  'foo[bar]': '123',
  'foo[baz]': '456',
  'quux': '789',
}

print getdict(D, 'foo')
# Returns: {'bar': '123', 'baz': '456'}
Ignacio Vazquez-Abrams
+2  A: 

You could use django.utils.datastructures.DotExpandedDict with inputs named category.1, category.2 etc. to do something similar, but I don't really see why you would if you ever have to validate and redisplay the information you're receiving, when using a django.forms.Form will do everything for you - appropriate fields will call the getlist method for you and the prefix argument can be used to reuse the same form multiple times.

insin
That does the job. Thanks!
Matt