我已經在兩個構成SelectField和StringField的組件中設置了DataRequired驗證。當html表單動作設置爲返回時,wtfform驗證停止工作下面的頁面
用戶在index
頁面上輸入的信息然後打算進入以下results
頁面。
驗證當index.html
文件form action
屬性設置爲""
工作。但是,在這種情況下,輸入的表單數據不會存儲在變量中並傳送到results
(結果頁面上的表字段顯示「無」)。
然而,當index.html
的form action
屬性設置爲results
在輸入的字段數據存儲和結轉到結果頁面,但DataRequired確認不再發生,大概是因爲HTML action屬性繞過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()])
好吧,這工作thanks-可你剛纔解釋了'** query'位,什麼是''**辦?歡呼 – nmh
@nmh **查詢與** kwargs相同 - https://stackoverflow.com/questions/1769403/understanding-kwargs-in-python;這裏是url_for如何使用它:http://flask.pocoo.org/docs/0.12/api/#flask.url_for – dm295