skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    import json
    
    details = data['details']
    list = json.loads(details)<==== transform the data into list of dictionaries
    for d in list:
        detail = Properties.objects.create(
            product = product,
            name = d["nameDetail"],
            value = d["valueDetail"],
        )
    

  2. JavaScript Arrays are Objects hence even when you console.log them, you will get an Object with keys as Array element indices and values as actual Array elements.

    To pass this over the wire as an array [1] the best option is to encode as JSON using JSON.stringify.

    details: JSON.stringify(details), <===== problem solved!

    [1] By array I mean data that has array representation [•••] which we all recognize.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search