Search code examples
pythonsqliteflasksqlalchemywtforms

My Custom flask ValidationError not working


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)

Returns

sqlalchemy.exc.IntegrityError

sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: user.username [SQL: INSERT INTO user (username, email, image_file, password) VALUES (?, ?, ?, ?)] [parameters: ('Kelvinasdhe', '[email protected]', 'default.jpg', '$2b$12$NusydBknOBkgkq60FJIyO.fsgIPnlk3HhB5n9kLAdczt4jvUtViiy')] (Background on this error at: http://sqlalche.me/e/gkpj)


Solution

  • There is a typo : valiate_username should be validate_username (same for email)

    And in validate_username username is a field. To obtain the value imputed, you have to use username.data :

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