Vue formdata() for multiple objects to be added on database from django serializer

Viewed 77

I want to add multiple objects to formdata so they can be added on the database at the same time.

This is my javascript code for sending the object

 addImages(id) {
      const formData = new FormData();
      this.imageArray.forEach((element) => {

        formData.append("image",element);
        formData.append("product", id);
      });
      
      let config = {
        headers: {
          Authorization: `Bearer ${this.$store.state.accessToken}`,
          "Content-Type": "multipart/form-data" 
        },
      };
      axios.post(`http://127.0.0.1:8000/images/`, formData, config,);
    },

The problem is that in the backend the information comes like this :

<QueryDict: {'product': ['31', '31'], 'image': [<InMemoryUploadedFile: allstar.jpg 

(image/jpeg)>, <InMemoryUploadedFile: cat.jpeg (image/jpeg)>]}>

And for it to be added to the database it should look similiar to this.

[{'product':'31','image': [<InMemoryUploadedFile: allstar.jpg (image/jpeg)]>},

{'product':'31','image':<InMemoryUploadedFile: cat.jpeg (image/jpeg)>]}>]

One solution that i came up with was to modify the data when i recived it in the backend

   data_list =[]
        new_data = dict(request.data)
        for x,y in zip(new_data['image'],new_data['product']):
            data_list.append({'image':x,'product':y})

I was wondering if there was a more cleaner solution that could be made when formdata was sent

0 Answers
Related