我最近做了类似的事情,在同一个模板中使用多个表单并调用了多个 render_template。每个表单在更改时提交并填充下一个表单。
如果您不想多次调用数据库,可以将其存储在会话变量中。
这没有经过测试,但大致如下:
class Firm(FlaskForm):
firm = SelectField('firm', coerce=str, validators=[InputRequired()])
class Prod(FlaskForm):
prod = SelectField('prod', coerce=str, validators=[InputRequired()])
class Spot(FlaskForm):
spot = SelectField('spot', coerce=str, validators=[InputRequired()])
@app.route
def route():
if form1.validate_on_submit():
form2.prod.choices = session.data.prodlistfunction
return render_template("/", form1=form1, form2=form2, form3=form3)
if form2.validate_on_submit():
form3.spot.choices = session.data.spotlistfunction
return render_template("/", form1=form1, form2=form2, form3=form3)
if form3.validate_on_submit():
do.something()
data=db.call()
session.data = data
form1 = Firm()
form2 = Prod()
form3 = Spot()
form1.choices = data.somefunction()
# give other forms blank choices to start off with
form2.choices = ["",""]
form3.choices = ["",""]
return render_template("/", form1=form1, form2=form2, form3=form3)
然后对于模板类似
<form>
{{ form1.csrf_token }}
{{ form1.firm(onchange='this.form.submit()') }}
</form>
<form>
{{ form2.csrf_token }}
{{ form2.prod(onchange='this.form.submit()') }}
</form>
<form>
{{ form3.csrf_token }}
{{ form3.spot(onchange='this.form.submit()') }}
</form>