Warm tip: This article is reproduced from stackoverflow.com, please click
django

Cannot access array passed by post

发布于 2020-03-27 10:17:36

I'm processing a form passing (by post) the data to a view. From the view if i print the whole request.POST object I get:

<QueryDict: {'csrfmiddlewaretoken': ['<omitted>'], 'doctype-name': ['a7'], 'doctype-validita': ['1'], 'projects': ['1', '2']}>

If i try to read or print request.POST['projects'] I get only the last value i.e. 2

Questioner
Sergio Raneli
Viewed
90
Willem Van Onsem 2019-07-03 21:38

A QueryDict is a dictionary-like collection, and thus can only return one element, since otherwise it does not (fully) respects the dictionary contracts.

You can use the QueryDict.getlist(..) method [Django-doc] here:

request.POST.getlist('projects')  # returns ['1', '2']

As the documentation says:

QueryDict.getlist(key, default=None)

Returns a list of the data with the requested key. Returns an empty list if the key doesn't exist and a default value wasn’t provided. It's guaranteed to return a list unless the default value provided isn’t a list.

The fact that it returns the last value is documented as well:

QueryDict.__getitem__(key)

Returns the value for the given key. If the key has more than one value, it returns the last value. Raises django.utils.datastructures.MultiValueDictKeyError if the key does not exist. (This is a subclass of Python’s standard KeyError, so you can stick to catching KeyError.)