I am trying to use AJAX to make a POST request to DRF.
One of my fields is a multiple select box. I can't seem to find a way to make the request work properly.
<select class="full-width" data-init-plugin="select2" id='roles' name="roles" multiple>
{% for role in roles %}
<option value="{{role.id}}">{{role.name}}</option>
{% endfor %}
</select>
I have tried posting the entire select box like below.
var roles = $('#roles').val();
I have also tried posting an array of the values.
var roles = $('#roles').find('option:selected').map(function(){return $(this).val()}).get();
My AJAX call looks like this:
$.ajax({
method: "POST",
url: "/v1.0/relationships/" + url,
data: {roles: roles}
)
My API view looks like this:
class RelationshipSingle(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):
"""
/relationship/{id}
Method Action
GET Return details of relationship with ID {id}.
POST Invalid option.
PATCH Edit the relationship.
DELETE Delete the relationship.
"""
queryset = Relationship.objects.all()
serializer_class = RelationshipSerializer
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
My serializer looks like this:
class RelationshipSerializer(serializers.ModelSerializer):
class Meta:
model = Relationship
fields = '__all__'