【问题标题】:Multiple Submit buttons in djangodjango 中的多个提交按钮
【发布时间】:2014-09-19 02:33:17
【问题描述】:

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

贴出来的PS值和显示的名字应该一致

例子:

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

在views.py中

from forms import ???

在 result_page.html 中

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

页面应该显示:

一个

两个

三个

【问题讨论】:

    标签: django forms python-2.7 button submit


    【解决方案1】:

    在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

    【讨论】:

    • 谢谢!这成功了。也许,我应该使用其他类型的按钮。基本上,我需要这个:当我按下 list1 中的一个项目时,我会在数据库中搜索它并在同一页面上返回相关内容。
    • 不客气!根据您评论中添加的信息,我为我的答案添加了一些额外的编辑。如果它回答了问题,您介意单击我的答案旁边的复选标记吗?谢谢你,祝你好运
    • 我更改了答案的编辑,检查一下,看来您真正需要的只是正确理解 HTML 表单,一切都会有意义:这就是您“发布所选元素”的方式
    • 感谢您的回复。看起来我需要使用按钮类型并按下其中一个,发送分配给它的值(不使用提交按钮)。我还需要保持模板的外观并显示新值(我想我需要为此使用会话)
    猜你喜欢
    • 2015-10-04
    • 2017-05-03
    • 2019-03-19
    • 2013-04-16
    • 2013-02-13
    • 2021-05-02
    • 2014-03-03
    • 1970-01-01
    • 2021-07-21
    相关资源
    最近更新 更多