Flask Python 按钮

新手上路,请多包涵

我正在尝试在页面上创建两个按钮。我想在服务器上执行不同的 Python 脚本。到目前为止,我只设法使用一个按钮 获取/收集

 def contact():
  form = ContactForm()

  if request.method == 'POST':
    return 'Form posted.'

  elif request.method == 'GET':
     return render_template('contact.html', form=form)

根据按下的按钮,我需要更改什么?

原文由 dojogeorge 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 462
2 个回答

给你的两个按钮相同的名称和不同的值:

 <input type="submit" name="submit_button" value="Do Something">
<input type="submit" name="submit_button" value="Do Something Else">

然后在您的 Flask 视图函数中,您可以知道哪个按钮用于提交表单:

 def contact():
    if request.method == 'POST':
        if request.form['submit_button'] == 'Do Something':
            pass # do something
        elif request.form['submit_button'] == 'Do Something Else':
            pass # do something else
        else:
            pass # unknown
    elif request.method == 'GET':
        return render_template('contact.html', form=form)

原文由 Miguel Grinberg 发布,翻译遵循 CC BY-SA 4.0 许可协议

这样做的适当方法:

 @app.route('/')
def index():
    if form.validate_on_submit():
        if 'download' in request.form:
            pass # do something
        elif 'watch' in request.form:
            pass # do something else

watchdownload 按钮放入模板中:

 <input type="submit" name="download" value="Download">
<input type="submit" name="watch" value="Watch">

原文由 Alexander.Iljushkin 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题