Flask WTF-Form无法验证

时间:2016-12-01 07:42:08

标签: python-3.x flask flask-wtforms

我制作了一个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'))

HTML

{% 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()])

1 个答案:

答案 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