svalemento
svalemento

Reputation: 722

How to parse multiple files in multipart form-data with django rest framework?

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

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

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:

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 is' a list.

If you perform indexing (like request.data[key]), then Python will call __getitem__ behind the curtains, and this will result in:

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.)

Upvotes: 3

Related Questions