FlaskPython按钮不响应

2024-07-02 11:37:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一页/联系人.html. 它有一个按钮,当我提交到第二页(算法.html)用户已登录。在第二页,我有两个按钮,但我不能让任何一个作出回应。这是我的代码:

@app.route('/contact', methods = ['GET', 'POST'])
def contact():
    form = ContactForm()

    if request.method == 'POST':
        return render_template('algo.html')
    if request.method == 'POST' and request.form['submit'] == 'swipeleft':
        print "yes"

打开联系人.html我有:

^{pr2}$

就这样算法.html我有:

<input type = "submit" name = "submit" value = "swipeleft" method=post>
<input type = "submit" name = "submit" value = "swiperight" method=post>

Tags: nameform算法inputifrequesthtmltype
3条回答

我想你的问题是:

if request.method == 'POST':
    return render_template('algo.html')
if request.method == 'POST' and request.form['submit'] == 'swipeleft':
    print "yes"

对于第一个if语句,它将始终返回True,并且函数将返回呈现的模板。它永远不会检查第二个if语句。在

只需切换位置,这样它就可以检查POST请求以及表单是否已提交。在

^{pr2}$

或者

if request.method == 'POST':
    if request.form['submit'] == 'swipeleft':
         print "yes"

    return render_template('algo.html')

编辑: 你犯了一个严重的错误:

<input type = "submit" name = "submit" value = "swipeleft" method=post>

更改为:

<form method="post" action="URL" > # change URL to your view url.
    <input type="submit" name="swipeleft" value ="swipeleft">
</form>

现在在您看来,请执行以下操作:

if request.method == 'POST' and request.form['swipeleft']:

在您的algo.html模板中,您需要将一个表单提交回同一个url /contact,因为在那里您要检查swipeleft的值:

<form action="{{ url_for('contact') }}" method="post">
   <input type = "submit" name = "submit" value = "swipeleft" />
   <input type = "submit" name = "submit" value = "swiperight" />
</form>

试试看:

if request.method == 'POST':
    if request.form.get('submit') == 'swipeleft':
        print "first part"
    elif request.form.get('submit') == 'swiperight':
        print "second part"
    return render_template('algo.html')

相关问题 更多 >