My current challenge involves a serializer class within DRF:
class ItemSerializer(serializers.ModelSerializer):
categories = serializers.PrimaryKeyRelatedField(many=True)
I am aiming to update the categories
of a model instance through 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
}
});
However, I'm encountering difficulty in formatting the categories
parameter correctly.
I attempted as illustrated in the above code, but the parameters do not transfer to the serializer; the categories
field remains empty in the serializer attributes.
In this scenario, the request parameter is a list, yet its name is categories[]
instead of simply categories
.
Another unsuccessful approach involved using JSON.stringify(categories)
, which led to a validation error in the serializer:
{"categories": ["Incorrect type. Expected pk value, received unicode."]}
It appears that in this case, the request parameter value becomes a string rather than a list.
Conversely, I was able to execute the PUT request successfully via the DRF browsable API, utilizing the parameter named
categories</code with a list as its value.</p>
<p>Could you provide guidance on how to properly send the parameter through ajax, ensuring that it appears in the request parameter as a list and under the name <code>categories
?
Thank you for your assistance!