简体   繁体   English

Django DRF从POST读取json吗?

[英]Django DRF read json from POST?

When I try to send data from a jquery POST I can get them from both side, js client and python django-rest-framework sefializer create method from backend 当我尝试从jquery POST发送数据时,我可以同时从js客户端和python django-rest-framework sefializer的后端获取数据。

console.log says: console.log说:

{
  "wo_r": [
    {
      "pk": "17635"
    },
    {
      "pk": "17637"
    }
  ]
}

the form data show dict as: 表单数据将dict显示为:

     {
  "wo_r": [
    {
      "pk": "17635"
    },
    {
      "pk": "17637"
    }
  ]
}:

django shell read: django shell读取:

<QueryDict: {'{\n  "wo_r": [\n    {\n      "pk": "17635"\n    },\n    {\n      "pk": "17637"\n    }\n  ]\n}': ['']}>

Why the data sent get this ":" at the end? 为什么发送的数据最后得到这个“:”?

this is the javascript part: 这是javascript部分:

  function creaol(indirizzo,val) {

  $.ajax({
      url: indirizzo,
      type: 'POST',
      dataType:'json',
      global: false,
      data :  val,
      //  data : {'wo_r':[
      //               {"pk": "17629"}, {"pk": "17630"},{"pk": "17631"}
      //          ]},
      success: function(result) {
          // Do something with the result
      }
  });
  }


  var dati = JSON.stringify(dict, null, 2);
  creaol(indirizzo, dati );

You are receiving the data wrong, look at the Querydict. 您收到的数据有误,请查看Querydict。

<QueryDict: {'{\n  "wo_r": [\n    {\n      "pk": "17635"\n    },\n    {\n      "pk": "17637"\n    }\n  ]\n}': ['']}>

The JSON is the dictionary key and the value is an empty list ['']. JSON是字典键,值是一个空列表['']。 Try in ajax call pass data like this: 试试这样的ajax呼叫传递数据:

data : {"wo_r": [{"pk": "17629"}, {"pk": "17630"},{"pk": "17631"}]}

and in django view read data as request.data Django Rest Frameword request parsing 并在Django视图中将数据读取为request.data Django Rest Frameword请求解析

Also put in your ajax call attribute contentType: 'application/json'. 还要放入ajax调用属性contentType:“ application / json”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM