我的自定义烧瓶ValidationError不起作用

时间:2020-04-28 10:51:15

标签: python sqlite flask sqlalchemy wtforms

form.py

class RegistrationForm(FlaskForm):
      username=StringField('Username',validators=[DataRequired(),Length(min=2,max=20)])
      email=StringField('Email',validators=[DataRequired(),Length(min=2,max=20),Email()])
      password=PasswordField('Password',validators=[DataRequired(),Length(min=8,max=20)])
      confirm_password=PasswordField('Confirm Password',validators= 
           [DataRequired(),Length(min=8,max=20),EqualTo('password')])
      submit=SubmitField('SignUp')

      def valiate_username(self,username):
          user=User.query.filter_by(username=username).first()
          if user:
              raise ValidationError('Username Exists')

      def valiate_email(self,email):
          user=User.query.filter_by(email=email).first()
          if user:
              raise ValidationError('Email exists, please Login or Click forgot password If you forgot')

routes.py

@app.route("/register", methods=['GET','POST'])
def register():
    form=RegistrationForm()
    if form.validate_on_submit():
        hpasskey=bcrypt.generate_password_hash(form.password.data).decode('utf-8')
        user=User(username=form.username.data,email=form.email.data,password=hpasskey)
        db.session.add(user)
        db.session.commit()
        flash(f'Account Created for {form.username.data}!','success')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)

返回

sqlalchemy.exc.IntegrityError

sqlalchemy.exc.IntegrityError:(sqlite3.IntegrityError)唯一约束失败:user.username [SQL:INSERT INTO用户(用户名,电子邮件,图像文件,密码)VALUES(?,?,?,?) [参数:('Kelvinasdhe','achiampon@gmail.com','default.jpg','$ 2b $ 12 $ NusydBknOBkgkq60FJIyO.fsgIPnlk3HhB5n9kLAdczt4jvUtViiy']] (此错误的背景位于:http://sqlalche.me/e/gkpj

1 个答案:

答案 0 :(得分:1)

有一个错字:valiate_username应该是validate_username(与电子邮件相同)

validate_usernameusername是一个字段。要获得估算值,您必须使用username.data

user=User.query.filter_by(username=username.data).first()