为什么StringField始终为None?

时间:2019-09-24 10:41:30

标签: python flask wtforms flask-bootstrap

我正在尝试使用Flask,WTForms和通过flask-Bootstrap提供的宏来读取表单。这在某些情况下有效,在另一些情况下(看似相似)却无效。当我检查特定StringField的内容时,它始终评估为None,从而导致InputRequired()验证失败。

forms.py:

from wtforms import Form, validators, \
                    StringField, PasswordField, SubmitField, \
                    SelectField, RadioField
from wtforms.fields.html5 import DateField
from wtforms.validators import ValidationError, InputRequired, NoneOf, \
                               EqualTo, Length, Optional

class TestForm(Form):
    name = StringField('Name', [validators.InputRequired(message='Please enter name!')])
    date = DateField('Date', format='%Y-%m-%d') #, default=date.today())
    address = StringField('Address')
    submit = SubmitField('Add')

test.py:

from flask import render_template, redirect, request
from flask_security import login_required
from application.routes import routes
from application.forms import TestForm

@routes.route('/test', methods=['POST', 'GET'])
@login_required
def test():
    form = TestForm()
    print(form.name.data)
    if request.method == 'POST' and form.validate():
        print("validated")
        return redirect("/")
    return render_template('test.html', title="Asset Manager", form=form)

test.html:

{% extends 'layout.html' %}

{% import "bootstrap/wtf.html" as wtf %}
{% block content %}
  <div class="container-fluid">
    <h3><u>Test:</u></h3>
    <br>
    <div class="container-fluid col-md-3">
      <form action="" method="POST" class="form" role="form" onsubmit="/">
        <div class="row">
          <div class="col-md-12">
            {{ wtf.form_field(form.name, form_type="inline", placeholder="Name") }}
          </div>
        </div>
        <div class="row">
          <div class="col-md-5">
            {{ wtf.form_field(form.date) }}
          </div>
        </div>
        <div class="row">
          <div class="col-md-12">
            {{ wtf.form_field(form.address) }}
          </div>
        </div>
        {{ wtf.form_field(form.submit, class="btn btn-primary") }}
      </form>
      {% for message in get_flashed_messages() %}
      <div class="alert alert-warning">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        {{ message }}
      </div>
    </div>
    {% endfor %}
  </div>
{% endblock %}

这总是显示 None ,因此即使输入名称并按 Add 按钮,也永远不会通过验证检查。 我尝试创建一个最小的示例(仍然存在相同的问题),但是我遗漏了应用程序的大部分内容,因此,如果您需要更多信息,请告诉我,我们将很乐意为您提供这些信息。

1 个答案:

答案 0 :(得分:0)

多亏了马克,我才找到了想念的地方。实例化表单时,我需要将请求作为参数传递。 所以这行

form = TestForm()

需要更改为

form = TestForm(request.form)

使应用程序正常工作。