Python Flask 和 WTForms:如何制作带有多个提交按钮的表单?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36090695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask & WTForms: How to make a form with multiple submit buttons?
提问by Digital
Imagine I need to build a travel planning form like this:
想象一下,我需要构建一个这样的旅行计划表:
Going from [_Picadily_Circus____]
Going to [_Marylebone_____]
(Starting by) (Arriving by) [5]:[30][pm]
Both (Starting by) (Arriving by) are submit buttons. The example is artificial to show a two-button usecase so let's not discuss usability.
两者 (Starting by) (Arriving by) 都是提交按钮。这个例子是人为地展示了一个两个按钮的用例,所以我们不讨论可用性。
How do I do this with Flask and WTForms?
如何使用 Flask 和 WTForms 执行此操作?
How to see which button was actually pressed?
如何查看实际按下了哪个按钮?
回答by pjcunningham
Your form's submit button's data value will be True
if it was pressed. See very simple example below of a form with two submit buttons and a single input field.
您的表单提交按钮的数据值将是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)
Here's the template file index.html:
这是模板文件 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>