'How to access array of files in request with Django Rest Framework
I'm sending a request from a React frontend to Python backend, in this request i'm sending a FormData() with an array of images, like this:
const data = new FormData()
images.forEach(image => {
data.append('images', image.arquivo)
})
data.append('product', JSON.stringify(product))
return recuperarInstanciaAxios(true).post(`${recuperarUrlBackend()}/products/`, data)
But I'm not being able to access this array of pictures in Python. Through PyCharm evaluate, request.FILES shows me a dict with an array 'images' within. But when I do request.FILES['images'] it returns me a single file. This is the python code:
def create(self, request):
try:
productData = json.loads(request.data['product'])
serializer = ProductSerializer(data=productData )
if serializer.is_valid():
product = serializer.save()
files = request.FILES['images']
for image in files:
product_image= {'image': image, 'product': product.id}
image_serializer = ProductImage(data=product_image)
if image_serializer .is_valid():
image_serializer .save()
else:
raise IntegrityError('Error :' +
serializer.errors.__str__())
return Response(serializer.data,
status=status.HTTP_201_CREATED)
else:
raise IntegrityError('Error:' +
serializer.errors.__str__())
except IntegrityError as exc:
print(exc)
return Response(exc.__str__(),
status.HTTP_412_PRECONDITION_FAILED)
It gives me an error because files is not iterable. Am I accessing the array in a wrong way?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
