简体   繁体   English

如何在视图中使用列表在Django中创建下拉列表

[英]How to create drop down in Django using the list in view

How can I create a dropdown in my template using the list values present in my view. 如何使用视图中显示的列表值在模板中创建下拉列表。 I do not want this to be present in my models.py. 我不希望这个出现在我的models.py中。 My views.py has generated some values which I would like to display in dropdown. 我的views.py生成了一些我想在下拉列表中显示的值。

Example: Say I have z=[1,2,3,4]. 示例:假设我有z = [1,2,3,4]。 I would like this value to be displayed in a drop down box in the template. 我希望此值显示在模板的下拉框中。

in the view: 在视图中:

def your_handler(request):
    z = [1, 2, 3, 4]
    return render(request, 'yourapp/your_template.html', {'z': z})

in the template: 在模板中:

<label>values in z<label>
<select id="the-id">
    {% for i in z %}
    <option value="{{ i }}">{{ i }}</option>
    {% endfor %}
</select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM