Search code examples
javascriptarraysdjangopost

Sending array of texts to Django, via POST, cannot get as array, getting string


I'm sending this data to Django, these texts are from multiple CKEditors

chk_vals = ["Some text","Other text"];
const data = new URLSearchParams();
data.append("csrfmiddlewaretoken", "{{csrf_token}}");
data.append("tmplData", JSON.stringify(chk_vals));

fetch(uri, {
        method: 'post',
        body: data,
    })
    .then(response => response.json())
    .then(data => {

It's from Chrome's network: tmplData: ["Some text","Other text"]

Now Django:

data = request.POST
templateArr = data.getlist('tmplData')
templateList = list(templateArr)

And the length of the templateList is 1, it is getting it as one string and I cannot split it with ',' because these texts can contain ',' too.

I also tried templateArr = data.getlist('tmplData[]')

and sending without JSON.stringify, but nothing works

data = request.POST
templateArr = data.getlist('tmplData[]')
templateList = list(templateArr)

and this variable templateArr is empty


Solution

  • Try sending values from frontend as individual fields like below:

    chk_vals = ["Some text", "Other text"];
    const data = new URLSearchParams();
    data.append("csrfmiddlewaretoken", "{{csrf_token}}");
    chk_vals.forEach(value => data.append("tmplData", value));
    fetch(uri, {
        method: 'POST',
        body: data,
    })
    .then(response => response.json())
    .then(data => console.log(data));

    And then try accessing it via your Django backend like below:

    templateArr = request.POST.getlist('tmplData') # templateArr = ["Some text", "Other text"]