defvalidate_username(self, username): user = User.query.filter_by(username=username.data).first() if user: raise ValidationError('That username is taken. Please choose a different one.')
from flask import render_template, url_for, redirect, request, flash from werkzeug.security import generate_password_hash, check_password_hash
@app.route('/register', methods=['GET', 'POST']) defregister(): form = RegistrationForm() if form.validate_on_submit(): hashed_password = generate_password_hash(form.password.data) user = User(username=form.username.data, password=hashed_password) db.session.add(user) db.session.commit() flash('Your account has been created! You are now able to log in', 'success') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
@app.route('/login', methods=['GET', 'POST']) deflogin(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user and check_password_hash(user.password, form.password.data): login_user(user) return redirect(url_for('dashboard')) else: flash('Login Unsuccessful. Please check username and password', 'danger') return render_template('login.html', title='Login', form=form)
@app.route('/dashboard') @login_required defdashboard(): return'Welcome to the Dashboard!'
This is a basic user registration and login function implementation. You need to create the corresponding HTML template files (such as register.html and login.html) to render the form. These steps and code logic provide a basic user authentication system that can be expanded and modified according to specific needs.