[英]I am trying to get the index value of the list item selected
<div class="container">
<br>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Names
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
{% for items in name %}
<a class="dropdown-item" href="{% url 'details' %}">{{ items }}</a>
{% endfor %}
</div>
</div>
name 是一个不同的列表,它可以有 2 个或 3 个或 n 个项目,所以我使用了 for 循环来显示下拉列表中的所有项目。现在我要做的是获取单击的下拉项目的索引. 例如,我单击下拉列表的第三项,我想将索引 2 传递给我的 views.py,因此当它重定向到 url“details.html”时,网页上显示的数据将从列表中提取,其中我想根据索引传递在下拉菜单中单击的项目的索引。
def details(request ):
name = request.session.get("name")
data = request.session.get("data")
txns = data["drop-downindex"]["txns"]
context ={"txns":txns ,"name1":name1}
return render(request , "details.html", context )
a session is what i am using to store data i am basically making an API in another function and storing the json data in data variable which is a list 1)the data list contains txns details for various names(dropdown) so when i click the下拉列表的第二项索引 1 应该在我的数据列表中 go 并获取列表项 2 或索引 1 的 txns
使用 enumerate 方法可以在列表中创建索引值。
name =['a','b','c','d','e']
for key,value in enumerate(name):
print(key , value)
Output:
1 a
2 b
3 c
4 d
5 e
更改您的 URL 使其接受索引参数。 就像是
url( r'^details/(?P<index>\d+)/$', myview, name='detail' )
更改您的视图以接受 index 参数
更改模板以将索引参数传递给url
:
<a class="dropdown-item" href="{% url 'details' index=index %}">{{ items }}</a>
我不清楚那个索引参数来自哪里,但它会在你的视图上下文中。 规范示例是一个详细视图,它接受一个 object id,通过迭代模板中的查询集获得:
... href="{% url 'details' id=object.id %}"
如果 name 是一个列表,您将name=enumerate(name)
传递给您的模板,for-loop 将是{% for index,items in name %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.