Home > Enterprise >  DRF parses number array as string
DRF parses number array as string

Time:12-05

When I make a POST request from JavaScript to my Django Rest Framework backend, my array of numbers is interpreted as string on the backend, causing this error: cargo: ["Incorrect type. Expected pk value, received str."]

This is how I make the request in JavaScript:

const data = new FormData();
data.append("cargo", JSON.stringify([1, 2]));
fetch(url, {method: "POST", body: data}).then(//<more code>

In my Django Rest Framework serializer, I define the cargo field like this:

cargo = serializers.PrimaryKeyRelatedField(                                                     
    many=True, queryset=models.CustomCargo.objects.all()                                        
)                                                                                               

On the backend request.data.get('cargo') is the string "[1,2]". I need to use multipart/form-data because I'm posting a file too, so I can't use application/json, which does work. Is there a way to fix this in the JavaScript code (I'd rather not convert strings to integers on the backend)?

CodePudding user response:

I ended up solving this by adding each item of the array to the FormData separately as strings:

[1, 2].forEach((cargo) => data.append("cargo", cargo.toString()));

If anybody has insight into why this works, please share.

  • Related