WTForm验证始终失败,验证器不会生成错误消息

时间:2019-06-20 06:37:53

标签: python flask flask-wtforms wtforms flask-bootstrap

我已经通过键入一些错误的东西测试了我的代码,但是一旦单击提交,屏幕上就不会产生错误消息

我也尝试键入正确的内容,但是一旦我检查了print,它表明验证总是失败的。 (已解决)

app:

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        print('validated')
        username = form.username.data
        password = bcrypt.generate_password_hash(form.password.data)
        email = form.mail.data
        print(username, password, email)
        flash("Successfully registered")
    else:
        print('validation failed')
    return render_template('register.html', form=form)

RegisterForm:

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Length, EqualTo, Email

class RegisterForm(FlaskForm):
    username = StringField('Username', [validators.Length(min=4, max=25)])
    password = PasswordField('Password', validators=[DataRequired(), Length(min=6, max=20)])
    confirm_password = PasswordField('Re-enter Password', validators=[DataRequired(), EqualTo(password)])
    email = StringField('Email', validators=[DataRequired(), Email()])
    submit = SubmitField('Register')

html:

{% extends 'base.html' %}
{% import "bootstrap/wtf.html" as wtf %}

{% block content %}
    <div class = 'container'>
        <br>
        <h1>Register Now</h1>
        <br>
        <div class="row">
            <div class="col-md-8">
                {{ form.hidden_tag() }}
                {{ wtf.form_errors(form, hiddens="only") }}

                {{ wtf.form_field(form.username) }}
                {{ wtf.form_field(form.password) }}
                {{ wtf.form_field(form.confirm_password) }}
                {{ wtf.form_field(form.email) }}
                {{ wtf.form_field(form.submit) }}
            </div>
        </div>
    </div>
{% endblock %}

我也尝试过

{{ wtf.quick_form(form) }}

但是它也不会生成错误消息。

1 个答案:

答案 0 :(得分:0)

您是否尝试过:

{{ wtf.form_errors(form) }}

根据docs

  

hiddens –如果为True,则也会渲染隐藏字段的错误。如果为“仅”,则仅渲染这些。

因此,您只显示隐藏字段的错误。