Search code examples
jsonhttprequestpython-3.7django-2.1

Accessing Lists in Django request.POST


I am having difficulty accessing all the data returned by my forms in my post function. I notice a significant discrepancy between what is displayed when I print request.POST vs. when my code accesses this data. Hopefully someone can explain this to me.

Output of print(request.POST):

print(request.POST)
<QueryDict: {'csrfmiddlewaretoken': ['AXMPO...'],
 'start_date': ['2019-03-01'], 'end_date': ['2019-03-26'], 
'reports': ['4', '1']}>

In order to examine the data my code is dealing with I used the json module to view the data. The behavior of my code during debugging conforms to this representation:

json.dumps(request.POST)
'{"csrfmiddlewaretoken": "AXMPO...",
 "start_date": "2019-03-01", "end_date": "2019-03-26",
 "reports": "1"}'

It all looks pretty similar until you see the "reports" value. The user selects these reports via an MultipleSelect widget on my form and my code is iterating through the id numbers provided. However, no matter how many reports I select I only get one ID. If anyone can explain why this is happening I would sincerely appreciate it.


Solution

  • Turns out this is a really old school issue. I could wish this was more prominent in the documentation though. The explanation by Simon Willson is below:

    """

    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. """ - Simon Willson, 13 years ago.