Code

Opened 8 years ago

Closed 8 years ago

Last modified 2 years ago

#1130 closed New feature (wontfix)

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

Reported by: elcio@… Owned by: adrian
Component: Core (Other) Version: master
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.

Attachments (0)

Change History (4)

comment:1 Changed 8 years ago by Simon Willison

  • Resolution set to wontfix
  • Status changed from new to closed

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 Changed 8 years ago by Simon Willison

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 Changed 8 years ago by rjwittams

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 Changed 2 years ago by anonymous

  • Easy pickings unset
  • Type changed from defect to New feature
  • UI/UX unset

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

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.