sharafjaffri sharafjaffri - 1 year ago 74
Ajax Question

How to extract list of lists in python django request.POST

I have posted data from ajax, data include csrfmiddlewaretoken(string), rcount(int) and list of prices. POSTED Data to Django view looks like this.

<QueryDict: {u'prices[2][]': [u'2128', u'5', u'06/09/2016', u'12:00 AM'], u'prices[0][]': [u'2147', u'5', u'06/09/2016', u'12:00 AM'], u'rcount': [u'59'], u'prices[1][]': [u'2108', u'5', u'06/09/2016', u'12:00 AM'], u'csrfmiddlewaretoken': [u'55qQByfBUxgII2nLJCkFZHHaJjJCF70p']}>

Now when I access rcount using following syntax, it works fine.


But when I try to access prices variable, It failed to get values.


This code is used to post data from HTML to Django View.

var records = []

records.push([2128, 5, '06/09/2016', '12:00 AM']);
records.push([2147, 5, '06/09/2016', '12:00 AM']);
records.push([2108, 5, '06/09/2016', '12:00 AM']);

var postData = {prices: records, rcount:59, csrfmiddlewaretoken: "{{ csrf_token }}"};
var posting = $.post('/myview/setprices/', postData);

How Can I access prices list?

From the answer of Rajesh Yogeshwar, I have used stringify and change postData as

var postData = {prices: JSON.stringify((records), rcount:59, csrfmiddlewaretoken: "{{ csrf_token }}"};
var posting = $.post('/myview/setprices/', postData);

And Now Prices are found as JSON value in request.POST and can be converted to python list using following syntax.

prices = request.POST.get('prices')
if prices:
prices = json.loads(prices)

This solved my problem.

Answer Source

In continuation to my comments on your original question, you can format data in such a way

var records = new Array();

records.push({'key1': 2128, 'key2': 5, 'key3': '06/09/2016', 'key4': '12:00 AM'})

You can push N number of records into your records array like this.

After that, you can replace this line

var postData = {prices: records, rcount:59, csrfmiddlewaretoken: "{{ csrf_token }}"};

with this

var postData = {prices: JSON.stringify(records), rcount:59, csrfmiddlewaretoken: "{{ csrf_token }}"};

In your views then, you can simply do

prices = request.POST.get('prices', None)
if prices:
    prices = json.loads(prices)

So now prices is list of dictionaries and you can do whatever you want it