How to append the fields inside an array to a formdata in react?

Viewed 382

I am a backend developer working mostly in Django-Rest-Framework. I have some issues while sending image in a post axios call. The frontend is sending objects like this here

{
            
            "merchant": 2,
            "category": [
                7
            ],
            "brand":7
        ,    "name":"picture55test",
            "best_seller":true,
            "top_rated":false,        
            "collection":10,
            "description":"abc",
            "featured": false,            
            "availability": "in_stock",
            "warranty": "no_warranty",
            "rating":5,
            "image":null,           
            "services": "cash_on_delivery",
            "variants": [
                {                
                "product_id": "OAXWRTZ_12C",
                "price": "500.00",
                "size": "not applicable",
                "color": "not applicable",
                "variant_image": null,
                "quantity": 10,
                "variant_availability": "available"
            },
            {                
                "product_id": "OGROUPIRZ_12C",
                "price": "888.00",
                "size": "not applicable",
                "color": "not applicable",
                "variant_image": null,
                "quantity": 10,
                "variant_availability": "available"
            }
            ]
        }

Now what I know is when we have to append a field to formdata we have to do like this:

handleSubmit = (e) => {
    e.preventDefault();
    console.log(this.state);
    let form_data = new FormData();
    form_data.append('image', this.state.image, this.state.image.name);
    form_data.append('name', this.state.name);
    form_data.append('services', this.state.services);
    let url = 'http://localhost:8000/api/addproducts';
    axios.post(url, form_data, {
      headers: {
        'content-type': 'multipart/form-data'
      }

Now, as you can see I have an array of data being sent for variants. How to append the fields inside the array of variants just like I am appending the name of the product in the above snippet??

In backend, I have used JsonParser and Formparser because image file is being sent. I dont know if that helps or not, but I put it like below:

class ProductAddAPIView(CreateAPIView):
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser,JSONParser,FormParser]
    queryset = Product.objects.all()
    serializer_class = AddProductSerializer

I have put the logic for creating the product objects as well as variants objects at the same time in serializer, but that is not necessary here I guess. I just need to know how to pass the image file which is inside an array, like variants array in the above data.

0 Answers
Related