我制作了一个Flask WTForm,允许我的用户确认一系列信息。我显示预填充信息的表单,用户可以修改它并提交表单。但是,即使没有发生错误(form.errors
为空),form.validate()
也始终返回False
。我做错了什么?
@app.route('/validation', methods=['GET', 'POST'])
def validation():
# initiate form
item = session.get('item', None)
form = AttrForm(request.form)
# pre-fill validation
form.price.data = item['price']
form.surface.data = item['surface']
form.rooms.data = item['rooms']
form.year.data = item['year']
# get area options and pre-fill
options = get_options()
form.subarea.choices = options
form.subarea.data = get_choice(options, item['subarea'])
# catch errors
if not form.validate_on_submit():
display = {'url': False, 'fill' : True, 'valid' : False}
return render_template('index.html', display=display, form=form)
# set new values
item['price'] = request.form['price']
item['surface'] = request.form['surface']
item['rooms'] = request.form['rooms']
item['year'] = request.form['year']
item['subarea'] = request.form['subarea']
session['item'] = item
return redirect(url_for('results'))
{% block attr_form %}
<h2>Attribute Form</h2>
<form action="/validation" method="POST">
<table>
<tr>
<td>Loyer (hors charges)</td>
<td>{{ render_field(form.price) }}</td>
</tr>
<tr>
<td>Surface</td>
<td>{{ render_field(form.surface) }}</td>
</tr>
<tr>
<td>Année de construction</td>
<td>{{ render_field(form.year) }}</td>
</tr>
<tr>
<td>Nombre de pièces</td>
<td>{{ render_field(form.rooms) }}</td>
</tr>
<tr>
<td>Quartier administratif</td>
<td>{{ render_field(form.subarea) }}</td>
</tr>
</table>
<input type=submit value="Je valide"></p>
</form>
{% endblock %}
{% macro render_field(field) %}
<dd>{{ field }}
{% if field.errors %}
<ul class=errors>
{% for error in field.errors %}
<ul>{{ error }}</ul>
{% endfor %}
</ul>
{% endif %}
</dd>
{% endmacro %}
class AttrForm(FlaskForm):
price = DecimalField('price', validators=[DataRequired()])
subarea = SelectField('subarea', coerce=int)
surface = DecimalField('surface', validators=[DataRequired()])
year = IntegerField('year', validators=[DataRequired()])
rooms = IntegerField('rooms', validators=[DataRequired()])
答案 0 :(得分:1)
首先确保您在烧瓶配置中定义了SECRET_KEY
。您需要执行此操作才能使CSRF
保护起作用。 http://flask-wtf.readthedocs.io/en/stable/csrf.html
其次,通过插入form.hidden_tag将csrf标记添加到html表单。
<form action="/validation" method="POST">
{{ form.hidden_tag() }}
<table>
<tr>
...
有关详细信息,请参阅http://flask-wtf.readthedocs.io/en/stable/quickstart.html。