Flask Login Form Example with Flask-WTF

  • Share this:

Code introduction


This is a login form example based on Flask and flask-wtf. It includes a form class `LoginForm` that uses `StringField` and `PasswordField` to collect username and password, and uses `InputRequired` and `Length` validators to ensure that the input is required and the length is appropriate. The `check_login_form` function is used to validate the form data and handle the login logic.


Technology Stack : Flask, flask-wtf, WTForms

Code Type : Flask Web Application

Code Difficulty : Intermediate


                
                    
from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import InputRequired, Length

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[InputRequired(), Length(min=4, max=25)])
    password = PasswordField('Password', validators=[InputRequired(), Length(min=8, max=25)])

def check_login_form(form):
    if form.validate_on_submit():
        # Assuming the form is valid, proceed with login
        return True
    else:
        # If the form is not valid, return False
        return False

# Flask route to handle login form
@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if check_login_form(form):
        return 'Login successful'
    return render_template('login.html', form=form)

if __name__ == '__main__':
    app.run(debug=True)