Opened 19 years ago

Closed 19 years ago

Last modified 13 years ago

#1130 closed New feature (wontfix)

request.POST["key"] returns only the last value of a list

Reported by: elcio@… Owned by: Adrian Holovaty
Component: Core (Other) Version: dev
Severity: normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

If I submit a list of inputs with the same name (as a checkboxes list) or request something like http://myserver/path?key=a&key=b&key=c I get strange things:

print request.POST
print request.POST["key"]
print dict(request.POST)["key"]

results:

{'key': ['a', 'b', 'c']}
c
['a', 'b', 'c']

I think request.POSTkey should return the same as dict(request.POST)key. The same with GET. Am I missing something?

I'm using rev. [1785] and the built-in Django server.

Change History (4)

comment:1 by Simon Willison, 19 years ago

Resolution: wontfix
Status: newclosed

This is a feature, not a bug. If you want a list of values for a key, use the following:

values = request.POST.getlist('key')

The reasoning behind this is that an API method should consistently return either a string or a list, but never both. The common case in web applications is for a form key to be associated with a single value, so that's what the [] syntax does. getlist() is there for the occasions (like yours) when you intend to use a key multiple times for a single value.

comment:2 by Simon Willison, 19 years ago

You can read more about this in the documentation comment at the top of the MultiValueDict class here: http://code.djangoproject.com/browser/django/trunk/django/utils/datastructures.py

I've opened ticket #1131 suggesting a repr method is added to MultiValueDict to make the special nature of the data structure more instantly clear.

comment:3 by rjwittams, 19 years ago

I've got to say that I think MultiValueDict is more trouble than it is worth. It seems to just lead to misunderstandings, and it also makes the implementation more complex (all the "needs list" stuff for formfields).

comment:4 by anonymous, 13 years ago

Easy pickings: unset
Type: defectNew feature
UI/UX: unset

It would be tremendous, if getlist() would also accept an optional fallback parameter, like get() does.

Note: See TracTickets for help on using tickets.
Back to Top