【问题标题】:How to extract list of lists in python django request.POST如何在 python django request.POST 中提取列表列表
【发布时间】:2016-10-09 23:05:55
【问题描述】:

我已经发布了来自 ajax 的数据,数据包括 csrfmiddlewaretoken(string)、rcount(int) 和价格列表。将数据发布到 Django 视图如下所示。

<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']}>

现在当我使用以下语法访问 rcount 时,它工作正常。

request.POST.get(rcount)

但是当我尝试访问价格变量时,它无法获取值。

request.POST.get(prices)
or
request.POST.getlist(prices)

此代码用于将数据从 HTML 发布到 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);

如何访问价目表?

根据 Rajesh Yogeshwar 的回答,我使用了 stringify 并将 postData 更改为

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

现在价格在 request.POST 中作为 JSON 值找到,可以使用以下语法转换为 python 列表。

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

这解决了我的问题。

【问题讨论】:

  • 查看看起来的数据,您正在 js 中的某个位置创建它并发布它。那么为什么不尝试使用 JSON.stringify() 对其进行 jsonify
  • 再想想你可以更好地格式化你的数据我的意思是而不是将项目作为列表记录,你可以使用字典然后对你的记录对象执行 JSON.stringify。
  • 能否提供示例代码?
  • 查看我发布的答案,它可能会解决您的问题,我已将键命名为 key1、key2,您可以将它们替换为有意义的东西。如果您在其中遇到其他问题,请告诉我

标签: python ajax django post


【解决方案1】:

继续我的 cmets 关于你原来的问题,你可以用这种方式格式化数据

var records = new Array();

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

您可以像这样将 N 条记录推送到您的 records 数组中。

之后,你可以替换这一行

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

有了这个

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

那么在你看来,你可以简单地做

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

所以现在价格是字典列表,你可以做任何你想做的事

【讨论】:

  • stringify 正在记录列表中添加额外的空字典。
【解决方案2】:

失败是因为您提供的字典中没有 'prices' 键。
取而代之的是键 'prices[2][]''prices[0][]''prices[1][]'。这些是普通的字符串。

您应该检查这些数据的发布方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-24
    • 2022-11-01
    • 2021-12-20
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 2018-05-26
    相关资源
    最近更新 更多