简体   繁体   中英

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

console.log says:

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

the form data show dict as:

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

django shell read:

<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:

  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: {'{\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 ['']. Try in ajax call pass data like this:

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

and in django view read data as request.data Django Rest Frameword request parsing

Also put in your ajax call attribute contentType: 'application/json'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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