javascriptdjangoreactjsdjango-rest-framework

How do I append a list to FormData?


I want to send image with additional data from React.js to Django backend. When I used FormData() to create my form data, it could not send the array (because it converted it to string). Here is my code:

let formData = new FormData();
        formData.append('text', postForm.text);
        formData.append('image', postForm.image, postForm.image.name);
        formData.append('privacy', postForm.privacy);
        formData.append('custom_list', postForm.customList);

        props.createPost(formData);

when I used this, I got this error:

{"custom_list":["Incorrect type. Expected pk value, received str."]}

So, I tried to create my own object to send to backend, but it can't handle image data. The code is:

const formData = {
            text: postForm.text,
            image: postForm.image,
            privacy: postForm.privacy,
            custom_list: postForm.customList
        }

This gave the following error:

{"image":["The submitted data was not a file. Check the encoding type on the form."]}

Is their any way I can send both list and image simultaneously?


Solution

  • You can send a list through FormData this way:

    postForm.customList.forEach(item => {
     formData.append('custom_list', item);
    });
    

    This will give you a custom_list array on the backend side.