Reputation: 1
I am trying to create a login system for my website. If a user makes an account with an already existing account the DB crashes and runs into an error. My problem is I don't know how I can make it so that it checks if that username has already been taken and flashes an error message if that name is already taken.
I am unsure what to add after if newUser:
, I'm new to Flask/Python so any help would go a long way.
Thank you.
@app.route('/signup', methods=['GET', 'POST'])
def signup():
form = SignupForm()
if form.validate_on_submit():
hashed_password = generate_password_hash(form.password.data, method='sha256')
db.session.add(newUser)
db.session.commit()
return render_template('index..html')
return render_template('signup.html', form=form)
Upvotes: 0
Views: 85
Reputation: 1242
You need to query the DB before creating a new user:
@app.route('/signup', methods=['GET', 'POST'])
def signup():
form = SignupForm()
if form.validate_on_submit():
hashed_password = generate_password_hash(form.password.data, method='sha256')
user = db.session.query(User).filter_by(username=form.username.data).scalar()
if user:
flash('Please choose another username')
else:
newUser = User(username=form.username.data)
db.session.add(newUser)
db.session.commit()
return render_template('index.html')
return render_template('signup.html', form=form)
Look at this line in the code:
user = db.session.query(User).filter_by(username=form.username.data).scalar()
Upvotes: 1