I am using formData with axios in my react frontend app in order to accommodate the image field. Tho, the data that I sent to the backend Django rest app is empty.
Frontend axios request
const addPost = (userInput, redirectTo) => dispatch => {
const input = [];
input[0] = userInput[0];
input[1] = userInput[1];
const postInput = userInput[2];
const formData = new FormData();
formData.append("title", postInput.title);
formData.append("excerpt", postInput.excerpt);
formData.append("content", postInput.content);
formData.append("status", postInput.status);
formData.append("image", postInput.image);
formData.append("created_by", postInput.created_by);
formData.append("category", postInput.category);
formData.append("slug", "");
input[2] = formData;
axios
.post(POST_ADD_URL, input)
.then(response => {
dispatch({type: ADD_POST_SUCCESS})
toast.success(
" added successfully!"
)
dispatch(getAllPost())
dispatch(push(redirectTo))
})
.catch(error => {
dispatch({type: ADD_POST_FAIL})
errorFilter(error)
dispatch(push(redirectTo))
})
}
This is mainly because I assigned the value of "formData to another variable "input1 = formData;
Backend code
def create(self, request):
# filter data
data = request.data
# filter user by email
author = data[0]
# filter category
category = data[1]
# filter post
post = data[2]
print("\npost data\n")
print(post)
print("\n\n")
serializer = PostSerializer(data=post)
serializer.is_valid(raise_exception=True)
# filter instances
user_instance = get_object_or_404(User, email=author['email'])
category_instance = get_object_or_404(Category, name=category['category'])
serializer.save(category=category_instance, created_by=user_instance)
return Response(serializer.data, status=status.HTTP_201_CREATED)
This is happening because axios converts the input array to json and sets the content-type of the request to application/json. Converting FormData to json will return an empty object. If you want to send FormData though a request use
// append the userInputs in the formData
axios.post(url, formData);