Creating a Flask-WTF Login Form

  • Share this:

Code introduction


This function creates a login form based on Flask-WTF, including username, password, and a 'Remember Me' checkbox field, and applies validations to these fields.


Technology Stack : Flask-WTF, StringField, PasswordField, BooleanField, InputRequired, Length, EqualTo, DataRequired

Code Type : Custom function

Code Difficulty : Intermediate


                
                    
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import InputRequired, Length, EqualTo, DataRequired

def create_login_form():
    # FlaskForm is a base class for creating forms with Flask-WTF
    # StringField creates a text input field
    # PasswordField creates a password input field
    # BooleanField creates a checkbox input field
    # InputRequired validates that the field is not left blank
    # Length validates that the input is within a specified length
    # EqualTo validates that the input matches another field
    # DataRequired validates that the field is not left blank

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

    return LoginForm