0

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__'

1 Answers1

0

I am supposing the value in multiple select box have manytomany relationship with your model. In Django-rest, if your are creating multiple objects, you will send list of objects. In your case, your Post data should look like

{
    role: [
        {"name": "ABC"},
        {"name": "CDF"}
    ]
}

$('select').val() return list of values. You need to convert it into list of objects. This can be done like this.

var selected_vals = $('#roles').val();

selected_vals = selected_vals.map(x => {
    return({name: x});
});
console.log(selected_vals)
Muhammad Hassan
  • 14,086
  • 7
  • 32
  • 54