如何在提交时验证Flask表格?

时间:2018-04-05 13:25:08

标签: python html css flask flask-wtforms

我已经生成了一个Flask表单,用于在我的CRUD应用程序中注册一个新用户。但是,即使填写了所有数据字段,Flask表单也会显示错误。我甚至在HTML代码中包含了{{ form.hidden_tag() }}。而且,这种异常行为突然开始了。当我添加2个新用户时,前两次工作正常。

以下是我使用的代码 - routes.py

@app.route("/register", methods=['GET','POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    regpass=app.config['REGISTRATION_KEY']
    if form.validate_on_submit():
        if form.passkey.data==regpass:
            user = User(username=form.username.data, email=form.email.data)
            user.set_password(form.password.data)
            db.session.add(user)
            db.session.commit()
            flash('Congratulations, you are now a registered user!')
            return redirect(url_for('login'))
        flash('Invalid Passkey!')
        return redirect(url_for('register'))
    return render_template('register.html', title='Register', form=form)

forms.py -

class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    password2 = PasswordField(
        'Repeat Password', validators=[DataRequired(), EqualTo('password')])
    passkey = PasswordField('Pass Key', validators=[DataRequired()])
    submit = SubmitField('Register')

    def validate_username(self, username):
        user = User.query.filter_by(username=username.data).first()
        if user is not None:
            raise ValidationError('Please use a different username.')

    def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user is not None:
            raise ValidationError('Please use a different email address.')

config.py -

import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
    SECRET_KEY = os.environ.get('SECRET_KEY')
    REGISTRATION_KEY=os.environ.get('REGISTRATION_KEY')

HTML -

{% extends "base.html" %}

{% block content %}
<br><hr>
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h1 id="signin">
                Register!
            </h1>
            <hr>
        </div> 
    </div>
    <form action="" method="post">
    {{ form.hidden_tag() }}
    <div class="row" id="form">
        <div class="col-md-12">
            {{ form.username.label }}<br>
            {{ form.username(size=32 , class_='form-fields') }}<br>
            {% for error in form.username.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
            <br>
            {{ form.email.label }}<br>
            {{ form.email(size=64, class_='form-fields') }}<br>
            {% for error in form.email.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
            <br>
            {{ form.password.label }}<br>
            {{ form.password(size=32, class_='form-fields') }}<br>
            {% for error in form.password.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
            <br>
            {{ form.passkey.label }}<br>
            {{ form.passkey(size=32, class_='form-fields') }}<br>
            {% for error in form.password2.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
            <br>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <span id='submit-field'><p >{{ form.submit(class_='submit-button-login') }}</p></span>
        </div>
    </div>
    </form>
</div>

{% endblock %}

如您所见,我在config.py文件中有REGISTRATION_KEY。在开始烧瓶应用之前,我在终端设置了REGISTRATION_KEY 这是显示错误的图像。 Error image

感谢和问候。

1 个答案:

答案 0 :(得分:1)

在Flask表单中,您需要设置password2字段,但在html中,您没有声明表单标记,因此也没有声明错误。添加{{ form.password2...将解决问题。