Django json发帖请求解析

时间:2018-05-09 17:03:49

标签: django post web request

我的客户端将此json作为帖子传递给django服务器:

data={  'supplier': supplier_name,
        'date': date,
        'payment':payment,
        'materials':[{"name":name,"qtd":qtd,"price":price},
                    {"name":name,"qtd":qtd,"price":price},
                    {"name":name,"qtd":qtd,"price":price}]
}

我正在使用推送材料:

data['materials'].push({"name":name,"qtd":qtd,"price":price});

我的django视图处理这样的数据:

supplier=request.POST.get('supplier')
date=request.POST.get('date')

当我尝试这样做时,材料内容为“无”:

materials=request.POST.get('materials')

如何在更进一步的代码中使用列表?

Ajax的发送方式如下:

$.ajax({
    type:"POST",
    url:"{% url 'validate_purchase' %}",
    data: data,
    dataType: 'json',
    success: function(data){
    }
});

2 个答案:

答案 0 :(得分:1)

如果您使用Content-Type: application/json传递数据,则可以json

访问request.body

示例:

(myblog)  ✘ ✝ ~/projects/myblog/base  up-sell±  curl --header "Content-Type: application/json" \
--request POST \
--data '{"supplier": "x", "date": "x", "materials": [{"price": "x", "qtd": "x", "name": "x"}, {"price": "x", "qtd": "x", "name": "x"}, {"price": "x", "qtd": "x", "name": "x"}], "payment": "x"}' \
http://localhost:8000/motor/upsell/set-upsell/ \
> -H "Content-Type: application/json"

views.py:

ipdb> import json
ipdb> json.loads(request.body)
{u'supplier': u'x', u'date': u'x', u'materials': [{u'price': u'x', u'qtd': u'x', u'name': u'x'}, {u'price': u'x', u'qtd': u'x', u'name': u'x'}, {u'price': u'x', u'qtd': u'x', u'name': u'x'}], u'payment': u'x'}

<强>更新

ajax调用示例

这是ajax函数,

data = {"supplier": "x", "date": "x", "materials": [{"price": "x", "qtd": "x", "name": "x"}, {"price": "x", "qtd": "x", "name": "x"}, {"price": "x", "qtd": "x", "name": "x"}], "payment": "x"}

$.ajax({
    type: 'POST',
    url: 'http://localhost:8000/motor/upsell/set-upsell/',
    data: JSON.stringify(data),
    contentType: "application/json",
    dataType: 'json'
});

Python代码,

ipdb> import json
ipdb> request.body
'{"supplier":"x","date":"x","materials":[{"price":"x","qtd":"x","name":"x"},{"price":"x","qtd":"x","name":"x"},{"price":"x","qtd":"x","name":"x"}],"payment":"x"}'
ipdb> json.loads(request.body)
{u'supplier': u'x', u'date': u'x', u'materials': [{u'price': u'x', u'qtd': u'x', u'name': u'x'}, {u'price': u'x', u'qtd': u'x', u'name': u'x'}, {u'price': u'x', u'qtd': u'x', u'name': u'x'}], u'payment': u'x'}
ipdb>

答案 1 :(得分:0)

要作为json发送的数据必须“字符串化”,因此您需要执行“JSON.stringify(data)”

$.ajax({
        type:"POST",
        url:"{% url 'validate_purchase' %}",
        data: JSON.stringify(data),
        dataType: "application/json; charset=UTF-8",
        success: function(data){
        }
    });