How to post a array to views.py

雨燕双飞 提交于 2019-12-13 07:56:37

问题


I am using for loop in my template and for different id of each record i am using arrays

{% 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 %}

Now when in my views i want to save this data to my database.But firstly i checked that whether my array return something or not.So i just try print that as.

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

or

 q = upload_form.data['custom']

but it gives me this error

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

but if i print this

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

then it display the value of array 1.

so please suggest me a better way to do this how i can display all values inside my array in views.py


回答1:


As upload_form.data is a dictionary, the key 'custom[]' simply doesn't exist. Try something like:

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

The dictionary custom_values holds now all your 'custom' form values.




回答2:


This is not an answer to question, but:

You are not posting an array, but different inputs whose name looks like accessing array. e.g. you are posting different input variables named custom[1], custom[2] etc. But custom is not an array, you will have to access inputs as custom[1] etc.

I'm not sure you want this or not!



来源:https://stackoverflow.com/questions/12833567/how-to-post-a-array-to-views-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!