Reputation: 3773
I'm using Django 1.10.2.
In a view, the below return []
print(request.POST.getlist('collected_already', None))
print(request.POST.getlist('collected_already[]', None))
print(request.POST.getlist('non_existent', None))
print(request.POST.getlist('non_existent[]', None))
I would expect None to be returned for the non_existent keys, and [] returned when an empty list is sent.
My workaround is to send and detect ['blank'] instead of [].
I'd appreciate pointers. With best wishes, Andy.
Upvotes: 2
Views: 3729
Reputation: 2678
I think getlist() takes default argument as None and returns empty list [ ] if key is not found.
Returns the data with the requested key, as a Python list. Returns an empty list if the key doesn’t exist and no default value was provided. It’s guaranteed to return a list of some sort unless the default value provided is not a list.
Upvotes: 0
Reputation: 308999
The getlist
returns the empty list []
by default. If you pass default=None
, then that is treated as 'no default specified', not as 'default to None`.
If you want to coerce the empty list []
to None
, then you could simply add or None
to the end of the expression.
print(request.POST.getlist('collected_already') or None)
This works because of the way Python evaluates boolean expressions. If x
and y
both evaluate to False, then x or y
returns y
.
Upvotes: 6