jQuery and django-rest-framework-bulk: send list

2019-07-07 01:40发布

问题:

I need to send a list of objects to a view using the django-restframework-bulk mixins:

class APIPicksView(mixins.ListModelMixin,
                          bulk_mixins.BulkCreateModelMixin,
                          generics.GenericAPIView):

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        print(type(request.DATA)) /* Should be list */
        if isinstance(request.DATA, list):
            # Custom logic here

In the browser side, I'm trying to send an array (list) of objects:

    var csrftoken = $.cookie('csrftoken');
    var data = [];
    for(var i = 0; i < picks.length; ++i) {
        data.push({pick:picks[i], priority:i, user:null});
    }

    $.ajax({
        type:"POST",
        url: "/api/foo/picks/",
        data: /* How should I format this data? */,
        sucess: function() { alert("Success!"); },
        dataType: "json",
        traditional:false, /* Should this be true? */
        crossDomain:false,
        beforeSend: function(xhr, settings) {
          xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    });

回答1:

If you look into request header, you will notice:

Content-Type:application/x-www-form-urlencoded; charset=UTF-8

This is incorrect type for json data.

You need to set the correct content type and serialize the data:

$.ajax({
    type: "POST",
    url: "/api/articles/",
    data: JSON.stringify(data),
    sucess: function() { console.log("Success!"); },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    crossDomain:false,
    beforeSend: function(xhr, settings) {
      xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
});