我在包含SelectField和StringField的两个wtform组件中设置了DataRequired验证。
用户在index
页面上输入的信息随后会显示在以下results
页面中。
当form action
文件中的index.html
属性设置为""
时,验证将起作用。但是,输入的表单数据不会存储在变量中并在此方案中传送到results
(结果页面上的表字段显示为“无”)。
但是,当form action
中的index.html
属性设置为results
时,会将输入的字段数据存储并转移到结果页面,但不再发生DataRequired验证,大概是因为html操作属性会绕过if form.validate_on_submit()
文件中的views.py
。
以下是index.html
,forms.py
和views.py
文件供参考。如何找到验证工作的方法,并将输入的数据转移到结果页面?
views.py文件:
####Index Page
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
exception = ""
try:
connectToDB()
except:
exception = 'Failure to connect to db'
form = StaffNames()
if not exception:
if form.validate_on_submit():
return redirect('/results')
return render_template('index.html',title='Search Page',exception=exception,form=form)
#####Results Page
@app.route('/results', methods=['GET', 'POST'])
def results():
form =StaffNames()
return render_template('results.html',
title='Results', form=form, staff_name = dict(staff_choices).get(form.staff.data))
的index.html:
<form action="" method="post" name="index">
<p> {{ form.hidden_tag() }} </p>
<p>{{ form.ranumber }} Enter RA Number</p>
{% for error in form.ranumber.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}<br>
<p>{{ form.staff }} Select your name</p>
{% for error in form.staff.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}<br>
<p><input type="submit" value="Search"></p>
</form>
forms.py:
from flask_wtf import Form
from wtforms import StringField, SelectField
from wtforms.validators import DataRequired
staff_choices=[("", ""), ('1', 'John Jones'), ('2', 'Chris Hughes'), (' 3', 'Lyn Tony')]
class StaffNames(Form):
ranumber = StringField('ranumber', validators=[DataRequired()])
staff = SelectField('staff',choices=staff_choices,validators=[DataRequired()])
答案 0 :(得分:1)
您是否尝试将表单数据作为查询字符串传递?
####Index Page
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
exception = ""
try:
connectToDB()
except:
exception = 'Failure to connect to db'
form = StaffNames()
if not exception:
if form.validate_on_submit():
query = {
'staff': form.staff.data,
'ranumber': form.ranumber.data
}
return redirect(url_for('results', **query))
return render_template(
'index.html', title='Search Page', exception=exception, form=form
)
#####Results Page
from flask import request
@app.route('/results')
def results():
ranumber = request.args.get('ranumber', None)
staff = request.args.get('staff', None)
return render_template(
'results.html', title='Results', staff=staff, ranumber=ranumber
)
这样您就可以完全跳过表单的动作属性
<form method="post" name="index">
...
</form>