实际上,当验证者不满意时,我们应该从 form.errors 中得到错误信息。但即使验证者不满意,我也会遇到任何错误。
app.py
@app.route('/home')
def home():
return render_template('home.html')
@app.route('/register',methods=['GET','POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
return redirect(url_for('home'))
return render_template('register.html',title='Register',form=form)
forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField,SelectField
from wtforms.validators import InputRequired, Length, Email, EqualTo,ValidationError
class RegistrationForm(FlaskForm):
username = StringField('Username',validators=
[DataRequired(),Length(min=2,max=20)])
email = StringField('Email',validators=[DataRequired(),Email()])
branches = SelectField('',[validators.input_required("Please choose your branch")],choices=[('-1','-- select --'),('0','cse'),('1','ece'),('2','mech'),('3','chem'),('4','mme'),('5','civil')])
password = PasswordField('Password',validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password',validators=[DataRequired(),EqualTo('password')])
submit = SubmitField('Sign Up')
register.html
<form method="POST" action="/register">
{{ form.hidden_tag() }}
{{ form.csrf_token }}
{{ form.username.errors }}
{{ form.username(class="form-control form-control-lg") }}
{{ form.email(class="form-control form-control-lg") }}
{{ form.password(class="form-control form-control-lg") }}
{{ form.confirm_password(class="form-control form-control-lg") }}
</form>
即使没有提供任何输入也不会产生错误。