FlaskPython按钮

2024-05-23 21:52:48 发布

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

我试图在一个页面上创建两个按钮。每一个我想在服务器上执行一个不同的python脚本。到目前为止,我只能用

def contact():
  form = ContactForm()

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

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

如果按了按钮,我需要更改什么?


Tags: form服务器脚本returnifrequestdefcontact
3条回答

为两个按钮指定相同的名称和不同的值:

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

然后在“烧瓶视图”功能中,您可以知道是哪个按钮用于提交表单:

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)

以防有人像我一样看到这个帖子。

<input type="submit" name="open" value="Open">
<input type="submit" name="close" value="Close">

def contact():
    if "open" in request.form:
        pass
    elif "close" in request.form:
        pass
    return render_template('contact.html')

简单,简洁,而且有效。甚至不需要实例化表单对象。

正确的方法是:

@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">

相关问题 更多 >