我想从下拉菜单中选择一个选项。
class GuestForm(Form):
name = StringField('Full Name', [validators.length(min=1, max=50)])
phone = StringField('Phone')
adults = StringField('Adults')
status = SelectField('Status', choices=[('BK', 'Booked'), ('CK', 'Cancelled')])
路线
@app.route('/edit_guest/<string:id>', methods=['GET', 'POST'])
def edit_guest(id):
# Create cursor
cur = mysql.connection.cursor()
# Get guest by id
result = cur.execute("SELECT * FROM guests WHERE id = %s", [id])
guest = cur.fetchone()
# Get form
form = GuestForm(request.form)
# Populate Guest form fields
form.name.data = guest['name']
form.phone.data = guest['phone']
form.adults.data = guest['adults']
form.status.data = guest['status']
if request.method == 'POST' and form.validate():
name = request.form['name']
phone = request.form['phone']
adults = request.form['adults']
status = request.form['status']
Jinja2模板
<form method="POST" action="">
<table style="width:100%">
<tr>
<td>{{render_field(form.name, class_="form-control")}}</td>
<td>{{render_field(form.phone, class_="form-control")}}</td>
<td>{{render_field(form.adults, class_="form-control")}}</td>
<td>{{render_field(form.status, class_="form-control")}}</td>
<tr>
</table>
</form>
当我在选择了值之后提交时,它在下拉值下面显示“不是有效的选择”。
答案 0 :(得分:0)
您的问题很难理解。对于尚未看到您的代码的人,很难组合代码片段。有很多很好的教程,可以使您对Flask Forms有很好的了解。我认为您应该在此花些时间以获得更好的理解。
尽管如此,我试图为您提供一个最小的运行示例。该示例创建一个您可以提交的表单。对于您的下一个问题,请尝试自己提出一个最小的例子。
dropdown.py
from flask import Flask
from flask import render_template_string, redirect, url_for
from flask_wtf import FlaskForm
from wtforms.fields import *
from wtforms.validators import *
class GuestForm(FlaskForm):
name = StringField('Full Name', [Length(min=1, max=50)])
phone = StringField('Phone')
adults = StringField('Adults')
status = SelectField('Status', choices=[('BK', 'Booked'), ('CK', 'Cancelled')])
app = Flask(__name__)
app.config['WTF_CSRF_ENABLED'] = False
@app.route('/edit_guest/<string:id>', methods=['GET', 'POST'])
def edit_guest(id):
# Instead of hard coding, read data from database based on id
# result = cur.execute("SELECT * FROM guests WHERE id = %s", [id])
# guests ...
guests = {'name': 'John', 'phone': '123456', 'adults': 2, 'status': 'BK'}
form = GuestForm(data=guests)
if form.validate_on_submit():
# Update data in database
# "UPDATE guests SET ... WHERE id = id
# access new data with **form.data
guests = form.data
return redirect(url_for("edit_guest", id="Test-id"))
return render_template_string(
"""
<html>
<head></head>
<body>
<form method="POST" action="">
<table style="width:100%">
<tbody>
{% for field in form %}
<tr>
<td>{{ field.label() }} </td>
<td>{{ field() }} </td>
</tr>
{% endfor %}
<tr>
<td></td>
<td><input type='submit'></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
""", form=form)
if __name__ == '__main__':
app.run(debug=True)