Skip to content Skip to sidebar Skip to footer

Php's Form Bracket Trick Is To Django's ___?

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

Solution 1:

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.

Solution 2:

Hardly pretty, but it should get the job done:

import re

defgetdict(d, pref):
  r = re.compile(r'^%s\[(.*)\]$' % pref)
  returndict((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'}

Solution 3:

Use request.POST.keys()

Solution 4:

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.

Solution 5:

I'm not a python expert but you might try

forkey,value in request.POST.iteritems() 
  doSomething....

Post a Comment for "Php's Form Bracket Trick Is To Django's ___?"