I have a serializer class using DRF:
class ItemSerializer(serializers.ModelSerializer):
categories = serializers.PrimaryKeyRelatedField(many=True)
and I want to update the categories
of an instance of the model via a RetrieveUpdateDestroyAPIView
using this serializer via an ajax request.
var categories = [1,2,3];
$.ajax({
url : "/api/items/id",
type: 'POST',
headers: {
'X-HTTP-Method-Override': 'PUT'
},
// Form data
data : {
'categories':categories
}
});
Unfortuntely I cannot understand how to format the categories
parameter.
I tried as shown in the code above and the parameters are not passed to the serializer, the field categories
in the serializer attributes is empty.
In this case, the request parameter is a list but the name is categories[]
and not categories
I also tried JSON.stringify(categories)
but in this case the serializer do not validate with error: {"categories": ["Incorrect type. Expected pk value, received unicode."]}
I figured out that in this case, the request parameter value is a string and not a list.
On the other hand, I am able to do the PUT request via the DRF browsable api and in this case the parameter is named categories
and it's value is a list.
Do you know how should I send the parameter with ajax, i.e. send the param so that is is present in the request parameter as a list an with name categories
?
Thank you very much!