django中的多个提交按钮

时间:2014-07-27 22:16:40

标签: django forms python-2.7 button submit

我是Django的新手我需要帮助使用for循环实现多个提交按钮。 我有一个元素列表,我需要迭代并创建提交按钮(或其他类型)。按其中一个按钮,将发布列表元素的值并更新页面。

张贴的PS值和显示的名称应该相同

示例:

list1 = ['one', 'two', 'three']
在views.py中

from forms import ???

在result_page.html

{% for el in list1 %}
"code to create buttons"
{% endfor %}

页面应显示:

一个

2

3

1 个答案:

答案 0 :(得分:0)

在views.py中,您可以将按钮名称传递给模板。使用字典和django提供的render_to_response方法。

在views.py中,在你的方法中(一个接受“请求”对象的文件

from django.shortcuts import render_to_response
....
context_dict = {list1: list1}  #just passing in the whole list for your for loop in result_page.html
return render_to_response('<directory_to_your_html_file>/result_page.html', context_dict, context)

然后在你的result_page.html

{% for el in list1 %}
<input type="submit" value="{{ el }}"> #double brackets to signify a django variable kinda like {% %}
{% endfor %}

不确定为什么这么多提交按钮,但如果你想使用任何其他输入法(例如单选按钮,复选框),则适用相同的逻辑

希望这有帮助!

编辑:好的,你添加的评论好像你会从

这样的东西中受益
 <form id="<a form id>" method="<either "POST" or "GET">" action="<directory to the script you are invoking>">
 {% csrf_token %} #don't worry about this one too much, its just django convention
 {% for el in list1 %}
 <input type="radio" name="a_name" value="{{ el }}">{{ el }}<br> #double brackets to signify a django variable   kinda like {% %}
 {% endfor %}
  <input type="submit" value="Search"> 
  </form>

尝试阅读HTML表单http://www.w3schools.com/html/html_forms.asp