Home > OS >  Send a dict from js to views: return querydict who bursts my dict
Send a dict from js to views: return querydict who bursts my dict

Time:11-13

I have a dict that I would like to send but I receive it in the form of a querydict whose content is no longer in the same form as the dict sent.

How can i have an object that i can manipulate simply ? I would like to add the elements in a database so I should do a for loop and add by index (key1, key2) but I can't get the real length when i do len(request.POST) it return 5.

.js

function sendData(event){
    const res = { 0:{"val1": 1, "val2":2}, 1:{"val1": 3, "val2":4}}
    ...
    $.ajax({
        ...
        data: {
            "result": res,
        },
        dataType: "json",
        ...
    }) }

views.py

def view1(request):
     print(request.POST)

$ <QueryDict: {'csrfmiddlewaretoken': ['...'], 'result[0][val1]': ['1'], 'result[0][val2]': ['2'], 'result[1][val1]': ['3'], 'result[1][val2]': ['4']}>

CodePudding user response:

You can get an iterable that will be easier to work with by calling lists() on the querydict.
You'll get a list of two element tuples. The first element being the key of your dict and the second the list of all values associated with the key.

for key, values in request.POST.lists():
   ...
  • Related