本文介绍了jQuery和django-rest-framework-bulk:发送列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用django-restframework-bulk mixins将对象列表发送到视图:

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

在浏览器端,我试图发送一个数组(list)的对象:

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);
        }
    });


推荐答案

如果您查看请求标题,您会注意到:

If you look into request header, you will notice:

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

这是json数据的错误类型。

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);
    }
});

这篇关于jQuery和django-rest-framework-bulk:发送列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 21:35