如何将数组发布到views.py

时间:2012-10-11 06:35:22

标签: django arrays django-templates django-views

我在我的模板中使用for循环,并且每个记录的不同id我正在使用数组

{% for item in product %}

<div class="register_div">


    <p><label for="id[{{ item.id }}]">{{ item.Name }} </label> <input type="text" name="custom[{{item.id}}]"/></p>

</div>

{% endfor %}

现在,在我的视图中,我想将这些数据保存到我的数据库中。但首先我检查了我的数组是否返回了某些内容。所以我只是尝试将其打印为。

q = upload_form.data['custom[]']

 q = upload_form.data['custom']

但它给了我这个错误

"Key 'custom[]' **OR** key custom not found in <QueryDict: {u'custom[2]': [u's'], u'custom[1]': [u'a'], u'price': [u''], u'title': [u''], u'customatt': [u'', u''], u'csrfmiddlewaretoken': [u'up4Ipd5L13Efk14MI3ia2FRYScMwMJLz']}>"

但如果我打印这个

q = upload_form.data['custom[1]']

然后显示数组1的值。

所以请建议我一个更好的方法来做到这一点我如何在views.py中显示我的数组中的所有值

2 个答案:

答案 0 :(得分:3)

由于upload_form.data是字典,因此关键字“custom []”根本不存在。尝试类似:

custom_values = {}    
for key, value in in upload_form.data.items():
    if key.startswith('custom'):
        custom_values[key]=value

字典custom_values现在包含所有“自定义”表单值。

答案 1 :(得分:0)

这不是问题的答案,但是:

您不是发布数组,而是名称​​看起来像访问数组的不同输入。例如您发布了名为custom[1]custom[2]等的不同输入变量。但custom不是数组,您必须以custom[1]等方式访问输入。

我不确定你是否想要这个!

相关问题