0

I'm working on a Django application that posts data to the server.

Here is the Python snippet:

def save(request):
    if request.method != 'POST':
        return HttpResponse('Illegal Request')

    print(request.POST.get('dataObj'))

    return JsonResponse({'status':200})

JQuery on the client side:

function submitQuoationClicked()
{
    dataObj = getQuotationInJSON()
    console.log(dataObj)
    token = $("input[name=csrfmiddlewaretoken]").val()
    $.ajax({
     type:"POST",
     url:"/quotations/save",
     data: {
        'csrfmiddlewaretoken': token,
        'dataObj' : dataObj,
     },
     success: function(data){
        if(data.status === 200)
            console.log("Good Work Falak!") //TODO Remove this line, FOR DEBUGGING ONLY
     }
});

function getQuotationInJSON()
{

    var data = {};

    data['title'] = $("#title").val()
    data['companyName'] = $("#company").val()
    data['addressLine1'] = $("#addressLine1").val()
    data['addressLine2'] = $("#addressLine2").val()
    data['city'] = $("#city").val()
    data['country'] = $("#country").val()

    data['date'] = $("#date").val()
    data['number'] = $("#number").val()
    data['validTill'] = $("#validTill").val()


    sections = getItemsData();
    data['sections'] = sections
    return data
}

function getItemsData()
{
    sections = []
    $("tr[id^='section']").each(function(index, element)
    {
        sectionId = $(element).attr('id').split('section')[1]
        name = $(element).find("#sectionName" + sectionId).val()
        section = {}
        section['name'] = name

        //Now get section items
        rowElems = $(".section" + sectionId)
        rows = []
        $(rowElems).each(function(index, row){
        if($(row).attr('id').indexOf('itemRow')>=0)
        {
            description = $(row).find("#description").val()
            quantity = $(row).find("#quantity").val()
            unitPrice = $(row).find("#unitPrice").val()
            margin = $(row).find("#margin").val()

            if(quantity!="" && unitPrice!="" && description!="" && margin!="")
            {
                row = {}
                row['description'] = description
                row['quantity'] = quantity
                row['unitPrice'] = unitPrice
                row['margin'] = margin

                rows.push(row)
            }
        }
    });

    section['items'] = rows;
    sections.push(section)
    });
    return sections
}

The JSON object is a quotation which has some basic details. It has some sections, each section has a name and a list of items in that section. Each item has some properties. But print(request.body) return 'None'. If I print(request.body), its prints the following text:

b'csrfmiddlewaretoken=ph8NQTz5uDtYaTSI5bDVAcdQ0MQtPrYWMMpIFOYP5eqD8urd2wtPRtxypBSnNg1J&dataObj%5Btitle%5D=Title&dataObj%5BaddressLine1%5D=&dataObj%5BaddressLine2%5D=&dataObj%5Bcity%5D=&dataObj%5Bcountry%5D=&dataObj%5Bdate%5D=&dataObj%5Bnumber%5D=&dataObj%5BvalidTill%5D=&dataObj%5Bsections%5D%5B0%5D%5Bname%5D=S1&dataObj%5Bsections%5D%5B0%5D%5Bitems%5D%5B0%5D%5Bdescription%5D=Hey&dataObj%5Bsections%5D%5B0%5D%5Bitems%5D%5B0%5D%5Bquantity%5D=2&dataObj%5Bsections%5D%5B0%5D%5Bitems%5D%5B0%5D%5BunitPrice%5D=9&dataObj%5Bsections%5D%5B0%5D%5Bitems%5D%5B0%5D%5Bmargin%5D=0'

I tried to get 'dataObj' from the request.POST.get('dataObj) but it returns None.

What is causing the problem?

Falak Marri
  • 211
  • 3
  • 15
  • For the sake of troubleshooting, here is the decoded body: `b'csrfmiddlewaretoken=ph8NQTz5uDtYaTSI5bDVAcdQ0MQtPrYWMMpIFOYP5eqD8urd2wtPRtxypBSnNg1J&dataObj[title]=Title&dataObj[addressLine1]=&dataObj[addressLine2]=&dataObj[city]=&dataObj[country]=&dataObj[date]=&dataObj[number]=&dataObj[validTill]=&dataObj[sections][0][name]=S1&dataObj[sections][0][items][0][description]=Hey&dataObj[sections][0][items][0][quantity]=2&dataObj[sections][0][items][0][unitPrice]=9&dataObj[sections][0][items][0][margin]=0'` – N. L. Long Nov 06 '17 at 15:57
  • Yes, I got it in this format too, but I think there is something terribly wrong with my JSON objects or the format in which it is being sent to the server. I'm unable to figure out. – Falak Marri Nov 06 '17 at 16:00

3 Answers3

0

While making a POST request using Ajax, add the following headers to your request:

ContentType:application/x-www-form-urlencoded
0

Your keys in the POST are going to look like this: request.POST.get('dataObj[title]')

See the answer on this question for details on how to handle the JSON in request.body Where's my JSON data in my incoming Django request?

N. L. Long
  • 180
  • 4
0

I have figured out the problem. The object that I was trying to pass were Javascript objects, not JSON. So the keys were appearing not in the expected format. So, I had to use JSON.stringify() method.

Here is the updated code: //Ajax call modified to:

$.post("/quotations/save", {csrfmiddlewaretoken: token, 
       data: JSON.stringify(dataObj)}, //Edited here
       function(result){
   if(result.status===200){
       console.log("Good Work Falak!")
   }
   else
   {
       console.log("Failed!")
   }

});
Falak Marri
  • 211
  • 3
  • 15