来自flask_wtf FlaskForm的form.validate_on_submit()无法正常工作

时间:2020-03-19 19:02:40

标签: python flask jinja2 wtforms

我正在尝试使用wtforms提交表单。我无法验证它。我还尝试使用{{ form.csrf_token }},但仍然无法正常工作。

app.config['SECRET_KEY'] = 'thisisthesecretkey'
class LoginForm(FlaskForm):
    username = StringField('username', validators=[
                           InputRequired(), Length(min=4, max=15)])
    password = PasswordField('password', validators=[
                             InputRequired(), Length(min=8, max=80)])
    remember_me = BooleanField('remember me')

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = forms.LoginForm()
    if form.validate_on_submit():
        return 'worked'

    return render_template('login.html', form=form)

我的神社:

        <form class="form-signin" action="/login" method="POST">
            {{ form.hidden_tag() }}
            {{ wtf.form_field(form.username) }}
            {{ wtf.form_field(form.password) }}
            {{ wtf.form_field(form.remember_me) }}
        </form>

        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
        <p class="mt-5 mb-3 text-muted text-center">© 2020</p>

2 个答案:

答案 0 :(得分:2)

您的action指示表单将发布到/login。我认为您想要action="/register"

答案 1 :(得分:0)

我在表单之前有一个and,我将它们放在表单内部,然后在表单字段中添加了a,这解决了问题,现在看起来像这样:

<form class="form-signin-heading"  method="POST" action="/login">
        <div class="text-center mb-4">
            <img class="mb-4" src="/static/logo.jpg" width="72" height="72">
            <h1 class="h3 mb-3 font-weight-normal">Heading1</h1>
        </div>

        <div class="container">
            {{ form.hidden_tag() }}
            {{ wtf.quick_form(form) }}
            <button class="btn btn-lg btn-primary btn-block" type="submit">Log in</button>
        </div>
    </form>