Flask by Example: WTForms Field Definitions
Flask 3.0+
Flask-WTF integrates WTForms with Flask. Defining forms as classes with typed fields makes handling form data robust, reusable, and secure against CSRF attacks.
Code
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired, Email, Length
class LoginForm(FlaskForm):
# StringField renders as <input type="text">
username = StringField('Username', validators=[
DataRequired(),
Length(min=4, max=25)
])
# PasswordField renders as <input type="password">
password = PasswordField('Password', validators=[
DataRequired()
])
# BooleanField renders as <input type="checkbox">
remember_me = BooleanField('Remember Me')
# SubmitField renders as <input type="submit">
submit = SubmitField('Sign In')
# In template:
# <form method="POST">
# {{ form.hidden_tag() }} <!-- CSRF Token -->
# <p>
# {{ form.username.label }}<br>
# {{ form.username(size=32) }}
# </p>
# ...
# </form>Explanation
Flask-WTF wraps the WTForms library to provide seamless integration with Flask. It handles automatic form rendering, data validation, and CSRF protection, making form handling much more secure and convenient.
Defining forms as classes with typed fields allows you to handle form data robustly. You can define fields like StringField or PasswordField and attach validators directly to them.
Key features provided by this integration include:
- Automatic Rendering: Render fields in HTML by calling them.
- Validation: Attach validators like
DataRequireddirectly to fields. - CSRF Protection: Automatically handled via
form.hidden_tag().
Code Breakdown
5
FlaskForm is the base class provided by Flask-WTF. It handles the request context and CSRF tokens automatically.7
The first argument
'Username' is the human-readable label. It is used when you render {{ form.username.label }}.25
{{ form.hidden_tag() }} is critical. It generates the hidden input field containing the CSRF token. Without this, form submission will fail validation.
