从Django的下拉菜单中检索多个值 [英] retrieve multiple values from Dropdown menu in Django
问题描述
我的模板中有一个很好的呈现形式的表单,其中包含一个下拉菜单和一个保存按钮,当我从下拉菜单中选择一个项目并单击保存"时,我将以下项目的网址传递给views.py,如下所示:
I have a form well rendered in my template with a dropdown menu and a save button, when i choose an item from the dropdown menu and click save, I pass to the views.py the url for that item, like this:
<select name="listxblocks">
{% for scname, desc in scenarios %}
<option value="{% url "workbench_show_scenario" scname %}">{{desc}}/{{scname}}</option>
{% endfor %}
</select>
现在,在views.py文件中,我可以检索所选项目及其值,
Now, in the views.py file i can retrieve the selected item and it's value,
if request.method == "POST": #checks if the request is a POST operation
url = request.POST['listxblocks']
但是我还想检索名称 scname 和描述 desc
but i want also to retrieve the name scname and the description desc
我尝试了隐藏字段,但是这使我的模板混乱了,我该怎么办?谢谢!
I tried with hidden field but it made my template messy, how can i do that? Thanks!
推荐答案
有两种方法可以从您的选择中检索所有信息.
There are two ways for retrive all information from your select.
1)从选择中获取 全部 数据.在视图中,使用以下代码:
1) Take all data from select. in the view use the following code:
variable = request.POST.getlist('listxblocks')
2)将多个"添加到您的选择中,例如
2) add "multiple" to your select like
<select name="listxblocks" multiple="multiple">
{% for scname, desc in scenarios %}
<option value="{% url "workbench_show_scenario" scname %}">{{desc}}/{{scname}}</option>
{% endfor %}
</select>
使用
url = request.POST['listxblocks']
您会找到一个包含所有选定选项的列表
you will find a list with all selected options
希望这会有所帮助:)
这篇关于从Django的下拉菜单中检索多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!