WTForms turns web-form definitions into reusable Python objects whose fields can render HTML and validate submitted data. Flask-WTF connects those forms to Flask handlers, reducing repetitive input-checking code. section 8.2.2
A login form can combine:
- An EmailField with required, length, and email-format validators. section 8.2.2
- A PasswordField that renders entered text as a password input. section 8.2.2
- A Flask handler that creates LoginForm, passes it to a template, and processes POST data. section 8.2.2
Login form
Define LoginForm with fields and validators, create it with form = LoginForm(), and render it through a template. The template can include the CSRF token, render fields, and display validation errors through a reusable macro. section 8.2.2
from flask_wtf import FlaskForm #1
from wtforms import PasswordField, #2
BooleanField, SubmitField #2
from wtforms.fields.html5 import EmailField #2
from wtforms.validators import DataRequired, #3
Length, Email, EqualTo #3
class LoginForm(FlaskForm): #4
email = EmailField( #5
"Email", #5
validators=[DataRequired(), Length( #5
min=4, #5
max=128, #5
message="Email must be between 4 #5
and 128 characters long" #5
), Email()], #5
render_kw={"placeholder": " "} #5
) #5
password = PasswordField( #6
"Password", #6
validators=[DataRequired(), Length( #6
min=3, #6
max=64, #6
message="Password must be between 3 #6
and 64 characters long" #6
)], #6
render_kw={"placeholder": “ “} #6
) #6
remember_me = BooleanField(" Keep me logged in") #7
cancel = SubmitField( #8
label="Cancel", #8
render_kw={"formnovalidate": True}, #8
) #8
submit = SubmitField("Log In") #9
Inspect the complete LoginForm definition, including field labels, validators, and rendered attributes. section 8.2.2
