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
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 thekey
doesn't exist and adefault
value wasn’t provided. It's guaranteed to return a list unless thedefault
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 thekey
has more than one value, it returns the last value. Raisesdjango.utils.datastructures.MultiValueDictKeyError
if thekey
does not exist. (This is a subclass of Python’s standardKeyError
, so you can stick to catchingKeyError
.)