I try to send a list of data from frontend via axios and recieve it in views.py with django.
The style of a data that I send:
[{ nameDetail: "1", valueDetail: "3" }, { nameDetail: "2", valueDetail: "4" }]
And this is when I console.log
before I pass the value to axios:
Array(2) 0: {nameDetail: 'Size', valueDetail: '2oz'}, 1: {nameDetail: 'Color', valueDetail: 'White'}, length: 2, [[Prototype]]: Array(0)
Request with axios:
const { data } = await axios.post(
`http://localhost:8000/api/products/product/add/`,
{
name: name,
brand: brand,
category: category,
description: description,
badge: badge,
price: price,
discount: discount,
countInStock: countInStock,
images: images,
details: details, <===== this is the data that i have a problem with
},
{
headers: {
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${userLogin.token}`,
},
}
)
But when I fetch it in views.py
with print(request.data)
the data transform:
<QueryDict: {'name': ['Electronic'], 'brand': ['ez'], 'category': ['Juices'], 'description': ['azea'], 'badge': ['promos'], 'price': ['22'], 'discount': ['2'], 'countInStock': ['2'], 'details[0][nameDetail]': ['Size'], 'details[0][valueDetail]': ['2oz'], 'details[1][nameDetail]': ['Color'], 'details[1][valueDetail]': ['White'], 'images[]': [<InMemoryUploadedFile: S33ef534d442d4a1d82ce7f52821f391aX (1).webp (image/webp)>]}>
Why is this happening and how can I can pass a list of data to the backend and loop through it?
Thank you.
2
Answers
Find the solution : just to transform the data in frontend like the previous comment thanks to him :) : details: JSON.stringify(details),
and in back end transform the data with:
JavaScript
Arrays
areObjects
hence even when youconsole.log
them, you will get anObject
with keys asArray
element indices and values as actualArray
elements.To pass this over the wire as an array [1] the best option is to encode as JSON using
JSON.stringify
.[1] By array I mean data that has array representation [•••] which we all recognize.