Reputation: 722
I am receiving an array with a few files. My request.data looks like this:
<QueryDict: {'image': [<TemporaryUploadedFile: image_1.png (image/png)>, <TemporaryUploadedFile: image_2.png (image/png)>]
However, if I try to parse images like this:
request.data['image']
I only can see the last image, and django rest framework recognize it as a file object, not a list. If I try to iterate over it all I can see is bytes.
I am using a ModelViewset and added this parsers
parser_classes = (MultiPartParser, FormParser)
Upvotes: 3
Views: 2515
Reputation: 477684
A QueryDict
has a special function to obtain all values associated with a specific key: getlist(key)
[doc]. So you can write it like:
request.data.getlist('image') # list of images
You can then process every image separately (for example in a for
loop).
Or like specified in the documentation:
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 theQueryDict.getlist(key, default=None)
default
value provided is' a list.
If you perform indexing (like request.data[key]
), then Python will call __getitem__
behind the curtains, and this will result in:
Returns the value for the given key. If the key has more than one value, it returns the last value. RaisesQueryDict.__getitem__(key)
django.utils.datastructures.MultiValueDictKeyError
if the key does not exist. (This is a subclass of Python's standardKeyError
, so you can stick to catchingKeyError
.)
Upvotes: 3