Reputation: 389
My client is passing this json as a post to django server:
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}]
}
I'm using push to put materials:
data['materials'].push({"name":name,"qtd":qtd,"price":price});
My django view handles data like this:
supplier=request.POST.get('supplier')
date=request.POST.get('date')
When I try to do this, the materials content is "none":
materials=request.POST.get('materials')
How can get a list use in further code?
Ajax is being sent like this:
$.ajax({
type:"POST",
url:"{% url 'validate_purchase' %}",
data: data,
dataType: 'json',
success: function(data){
}
});
Upvotes: 0
Views: 9692
Reputation: 389
Data to be sent as json must be "stringified", so you need to do "JSON.stringify(data)"
$.ajax({
type:"POST",
url:"{% url 'validate_purchase' %}",
data: JSON.stringify(data),
dataType: "application/json; charset=UTF-8",
success: function(data){
}
});
Upvotes: 2
Reputation: 8400
If you are passing data using Content-Type: application/json
, You can access json
from request.body
Example:
(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'}
Update:
Example by ajax call
Here is ajax function,
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 code,
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>
Upvotes: 2