烧瓶& WTForms:如何使用多个提交按钮制作表单?

时间:2016-03-18 17:27:45

标签: python flask wtforms flask-wtforms

想象一下,我需要建立一个这样的旅行计划表:

Going from [_Picadily_Circus____]
Going to [_Marylebone_____]
(Starting by) (Arriving by) [5]:[30][pm]

两者(开始)(到达)是提交按钮。该示例是人为的,以显示一个双按钮用例,所以我们不讨论可用性。

如何使用Flask和WTForms进行此操作?

如何查看实际按下了哪个按钮?

1 个答案:

答案 0 :(得分:10)

如果已按下,则表单的提交按钮的数据值将为True。请参阅下面一个非常简单的示例,其中包含两个提交按钮和一个输入字段。

from flask import Flask, render_template, flash
from flask.ext.wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'well-secret-password'


class MyForm(Form):
    name = StringField(label='Name', validators=[DataRequired()])
    starting = SubmitField(label='Starting')
    ending = SubmitField(label='Ending')


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

    if form.validate_on_submit():
        print "Starting data Value : {value}".format(value=form.starting.data)
        print "Ending data Value : {value}".format(value=form.ending.data)
        flash(
            "You submitted name {name} via button {button}".format(
                name=form.name.data,
                button="Starting" if form.starting.data else "Ending"
            )
        )

        return render_template('index.html', form=form)

    if form.errors:
        for error_field, error_message in form.errors.iteritems():
            flash("Field : {field}; error : {error}".format(field=error_field, error=error_message))

    return render_template('index.html', form=form)


if __name__ == '__main__':
    app.run(debug=True)

这是模板文件index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    {% with messages = get_flashed_messages() %}
      {% if messages %}
        <ul class=flashes>
        {% for message in messages %}
          <li>{{ message }}</li>
        {% endfor %}
        </ul>
      {% endif %}
    {% endwith %}

    <form method="POST" action="{{ url_for('index') }}">
        {{ form.csrf_token }}

        {{ form.name.label }} {{ form.name(size=20) }}
        <br><br>
        {{ form.starting }}
        {{ form.ending }}

    </form>
</body>
</html>