代码之家  ›  专栏  ›  技术社区  ›  PVG

django中的多个提交按钮

  •  0
  • PVG  · 技术社区  · 11 年前

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

    发布的PS值和显示的名称应相同

    例子:

    list1 = ['one', 'two', 'three']
    

    视图.py

    from forms import ???
    

    在result_page.html中

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

    页面应显示:

    1 回复  |  直到 11 年前
        1
  •  1
  •   Fan Ma    11 年前

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

    在views.py中,在您的方法(接受“request”对象的方法

    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