Proposal: if form name is like "name[key]", convert to dict in request.POST

12 views
Skip to first unread message

Rob Hudson

unread,
Feb 9, 2007, 3:26:11 PM2/9/07
to Django developers
This is obviously borrowed from PHP but I think there are useful
reasons to copy this behavior.

The idea...

If one constructs their HTML forms, naming their form elements as
"name[key]" like so:

<input type="text" name="f[name]">
<input type="text" name="f[address]">
<input type="text" name="f[city]">
etc.

Django would then convert this to a dictionary of form:

f = {
'name': 'value of f[name]',
'address': 'value of f[address]',
'city': 'value of f[city]'
}

This is also useful for grouping multiple select boxes:

<select multiple name="selects[]">
<option value="1">One</option>
<option value="2">Two</option>
<option value="2">Three</option>
</select>

(I'm not sure how Django handles multiple selects currently.)

Processing within Django, to me, becomes simpler, and one can do
things like the following rather than iterating over all items in
request.POST:

if request.POST.has_key('f'):
for k,v in request.POST['f'].iteritems():
# process key/value pairs in some way

Grouping your forms into dicts like this also lets you do iterative
logic while avoiding other POST items (eg: input type=submit values or
X,Y coordinates).

I'm not sure how this would tie in with newforms since we're not using
Django's forms and validation (at least for now).

Cheers!
Rob

SmileyChris

unread,
Feb 9, 2007, 5:54:44 PM2/9/07
to Django developers
Hi Rob, there's similar functionality in Django already (but it's
undocumented afaik) using a custom data structure called
DotExpandedDict:
http://code.djangoproject.com/browser/django/trunk/django/utils/datastructures.py#L215

I just opened a ticket regarding it's undocumented nature.

Rob Hudson

unread,
Feb 9, 2007, 7:41:25 PM2/9/07
to django-d...@googlegroups.com

Interesting. I'm guessing it's not wired up to request.POST... I tried
naming my form like name="name.key" and got no DotExpandedDict love. :)

Thanks,
Rob

SmileyChris

unread,
Feb 9, 2007, 8:04:07 PM2/9/07
to Django developers
On Feb 10, 1:41 pm, Rob Hudson <treborhud...@gmail.com> wrote:
> Interesting. I'm guessing it's not wired up to request.POST... I tried
> naming my form like name="name.key" and got no DotExpandedDict love. :)

You'd just do the following line:
post = DotExpandedDict(request.POST)

then you'll have some love.

Reply all
Reply to author
Forward
0 new messages