1

I am creating a nested dict in javascript and then send it with an Ajax call to one of my Django methods.

The dict is created like this:

var dictData = {};
$('#selector').each(function() {
            assistance1Data[$(this).attr('id')] = parseInt($(this).val());
        });

var formData = {};
formData["name"] = name;
formData["task_id"] = task_id;
formData["description"] = $("#description").val();
formData["nestedDict"] = dictData;

$.ajax({
     type : 'POST',
     url : '/taskmanagement/changeName/',
     dataType : 'html',
     data: formData,
     success : function(data){
          return true;
          }
     });

This all works fine until here. And it also works fine inside the views.py function using, for example, request.POST["name"]. I need to access the dict though, but as soon as I get the queryDict, it looks something like this:

<QueryDict: {u'description': [u'desc'], u'task_id': [u'1'], u'inCharge': [u'1'], u'nestedDict[valueFromDictData_1]': [u'2'], u'nestedDict[valueFromDictData_0]': [u'1'], u'name': [u'someName']}>

What I would need would be something like key1: [key2_1: 1, key2_2: 2] as dicts are usually structured instread of 'key1[key2_1']: 1 which makes the whole thing completely useless.

Hi Hi
  • 366
  • 4
  • 20
  • So what's the exact problem that you are trying solve? I understand your code but don't get your question. – Shang Wang Aug 18 '15 at 16:07
  • Well, I was wondering what is causing the dict to "break", but it seems as if you can't send anything besidey key:value with Post and therefore there is no direct solution for it. Now it is just fixing the QueryDict it seems. – Hi Hi Aug 18 '15 at 16:09
  • you need to understand what jQuery is actually sending in the body of the post request (look in browser dev tools) ...usually if you want to send a nested dict you should encode as json... Django will only give you decoded _form_ data in `request.POST` ...for a json object you should look in `request.body`... see similar question answered here: http://stackoverflow.com/a/3020756/202168 – Anentropic Aug 18 '15 at 16:15
  • It's not breaking, it's just how the `QueryDict` output looks like. If you do `request.POST['description']`, you will get a single value `'desc'`. You still use it as a normal dictionary, please try it out. – Shang Wang Aug 18 '15 at 16:21
  • @ShangWang as mentioned in my post, that is working :) I was just struggling with nested dicts since I wasn't aware of how jQuery sends it and thought it is caused by the queryDict object. – Hi Hi Aug 18 '15 at 17:22
  • 1
    @Anentropic Yeah, I educated myself now about how jQuery sends data and why it looked like this. I was searching at the wrong place before, but shortly after I asked my question found out that it is caused by. I now just added a JSON string of the dict to the key instead of trying to add the dict directly. Not sure if there is a better way to do it, but it works :) – Hi Hi Aug 18 '15 at 17:22

0 Answers0