【问题标题】:Cannot get multiple submit buttons to work in django form无法让多个提交按钮以 django 形式工作
【发布时间】:2017-05-14 01:13:09
【问题描述】:

我在这里看到了这个:

How can I build multiple submit buttons django form?

我试图在自己的代码中模仿(我认为我不太了解 request.POST 对象)

来自views.py的片段:

def globe(request):

    if request.method == 'POST':
        #for key, value in request.POST:
        #    print (key,value)

        if 'LoadLayer' in request.POST:
            print 'LOADED LAYER'
        elif 'notloadlayer' in request.POST:
            print 'not loaded layer'
        else:
            print 'BLARG' #hits this all the time...

然后是html:

     <form action="/" method="post" id="form">{% csrf_token %}
           <!--  {{ form.as_table     }} -->
            <table>
                {% for field in form %}
                <tr><td><font color="white">{{field}}</font></td></tr>
                {% endfor %}
            </table>
            <input type="submit" name="LoadLayer" value="Load Entities" />
            <input type="submit" name="notloadlayer" value="Export KML" />
        </form>

所以,是的,request.POST 对象中从来没有这些东西(我在 cmets 中尝试打印出字典中的项目,但它从未打印过它所说的太多内容或一些此类错误)。

不确定我遗漏了什么或做错了什么?

【问题讨论】:

  • 为什么要在 POST 中?它来自哪里?它根本不会出现在您的模板中
  • 我确实更改了 html 代码(发布了较旧的测试版本)。它现在在模板中,抱歉我弄错了(来自不同的测试)
  • 所以更新了代码,还是没有骰子。

标签: jquery python django django-forms


【解决方案1】:

使用以下代码

对于 HTML 和 Jquery

<form action="/" method="post" id="form">{% csrf_token %}
    <!--  {{ form.as_table     }} -->
    <table>
        {% for field in form %}
        <tr><td><font color="white">{{field}}</font></td></tr>
        {% endfor %}
    </table>
    <input type="checkbox" name="hidden_checkbox" id="hidden_checkbox" style="display:none"/>
    <input type="button" value="Load Entities" data-action="true"/>
    <input type="button" value="Export KML" data-action="false"/>
</form>

<script>
    $('input[type="button"]').click(function(){
        $('#hidden_checkbox').prop('checked', JSON.parse($(this).attr("data-action")));
        $('form').submit();
    });
</script>

对于 Django

def globe(request):

    if request.method == 'POST':
        if request.POST.get('hidden_checkbox'):
            print 'LOADED LAYER'
        else:
            print 'not loaded layer'

【讨论】:

    猜你喜欢
    • 2015-10-02
    • 2017-03-19
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 2015-06-14
    相关资源
    最近更新 更多