Creating a Simple Login Form with Flask-WTF

  • Share this:

Code introduction


This code example demonstrates how to create a simple login form using Flask-WTF. It includes username, password, and remember me checkboxes, and uses WTForms validators to ensure the validity of the input.


Technology Stack : Flask, Flask-WTF, WTForms

Code Type : Flask app

Code Difficulty : Intermediate


                
                    
from flask import Flask, render_template, request
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import InputRequired, Length, Email, EqualTo

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

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[InputRequired(), Length(min=4, max=15)])
    password = PasswordField('Password', validators=[InputRequired(), Length(min=8, max=80)])
    remember = BooleanField('Remember Me')

def login_form():
    # This function creates a login form using Flask-WTF
    # It includes username, password, and remember fields with respective validators

    form = LoginForm()
    return form

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = login_form()
    if form.validate_on_submit():
        # If the form is valid, process the form data
        print('Username: ', form.username.data)
        print('Password: ', form.password.data)
        return 'Login Successful'
    return render_template('login.html', form=form)

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