Home > other >  Custom Flask Validation Error not triggering getting Unique constraint error instead
Custom Flask Validation Error not triggering getting Unique constraint error instead

Time:08-20

I have created a registration form with validation but instead of this error Unique Constraint error is coming how can I fix this

Below is the register class

class Registerform(FlaskForm):
    username = StringField(label="Username", validators=[
        Length(min=3, max=20), DataRequired()])
    password1 = PasswordField(label="Password", validators=[
        Length(min=6, max=20), DataRequired()])
    password2 = PasswordField(label="Confirm Password", validators=[
        EqualTo('password1', message='Both password fields must be equal!'), DataRequired()])
    Submit = SubmitField(label='Submit')

    def validate_existing_user(self, username):
        checkexisting = User.query.filter_by(username=username.data).first()
        print(checkexisting)
        if checkexisting:
            raise ValidationError(
                "Oops Username already exists please try with a new Username")

Below is the registration route

@app.route("/register", methods=['POST', 'GET'])
def registerpage():
    form = Registerform()

    if form.validate_on_submit():
        usernameinput = form.username.data
        userpasswordinput = form.password1.data
        hashedpass = bcrypt.generate_password_hash(userpasswordinput)
        print(f"Normal pass is {userpasswordinput} & its hash is {hashedpass}")
        table_row = User(username=usernameinput,
                         password_hash=hashedpass, )

        db.session.add(table_row)
        db.session.commit()
        print("User added successfully")
        flash('User added successfully you can Login now',
              category='success')
        return redirect(url_for('login_page'))



    return render_template("registration.html", title='Registration', form=form)

Below is the DB model its sqllite

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password_hash = db.Column(db.String(120), nullable=False)

    def __repr__(self):
        return '<Username %s> <pwd %s>' % (self.username, self.password_hash)

Kindly assist I am new to flask

CodePudding user response:

The Documentation explains how to build a custom validator. The key is to name the validation methode like the attribute of your form. So instead of using validate_existing_user() you have to name the methode validate_username. That way wtforms will know that it hast to map the custom-validation methode to the username attribute.

  • Related