Form Handling — Flask-WTF
In this chapter you will learn to handle forms in a standardized way with Flask-WTF: defining form classes, automatic CSRF protection, field validation, and error messages.
Why Use Flask-WTF?
The registration and login forms in the previous chapter were handwritten: manually getting values from request.form.get() , manually validating, and manually displaying errors.
Flask-WTF wraps WTForms for Flask, providing:
- Form class definitions, with fields + validation rules managed centrally
- Automatic CSRF protection
- Render fields and error messages in templates
form.validate_on_submit()Unified handling of GET/POST detection and validation
Installation and Configuration
(venv) $ pip install flask-wtf
Configure SECRET_KEY in app.py (CSRF Token depends on this key):
Example
File path: app.py
app.
config
[
'SECRET_KEY'
]
=
'your-secret-key'
Use an environment variable in production
app.
config
[
'WTF_CSRF_ENABLED'
]
=
True
Enabled by default; declare it explicitly
Define Form Classes
Example
File path: app/forms.py (new file)
from
flask_wtf
import
FlaskForm
from
wtforms
import
StringField
,
PasswordField
,
EmailField
,
BooleanField
from
wtforms.
validators
import
DataRequired
,
Length
,
,
EqualTo
,
ValidationError
from
app.
models
import
User
class
RegisterForm
(
FlaskForm
)
:
"""Registration Form"""
username
=
StringField
(
'Username'
,
validators
=
[
DataRequired
(
message
=
'Username cannot be empty'
)
,
Length
(
min
=
3
,
max
=
50
,
message
=
'Username must be 3-50 characters long'
)
]
)
=
EmailField
(
'Email'
,
validators
=
[
DataRequired
(
message
=
'Email cannot be empty'
)
,
(
message
=
'Please enter a valid email address'
)
]
)
password
=
PasswordField
(
'Password'
,
validators
=
[
DataRequired
(
message
=
'Password cannot be empty'
)
,
Length
(
min
=
6
,
message
=
'Password must be at least 6 characters'
)
]
)
confirm_password
=
PasswordField
(
'Confirm Password'
,
validators
=
[
DataRequired
(
message
=
'Please enter the password again'
)
,
EqualTo
(
'password'
,
message
=
'The two passwords do not match'
)
]
)
Custom validator: check whether the username is already registered
def
validate_username
(
self
,
field
)
:
if
User.
query
.
filter_by
(
username
=
field.
data
)
.
first
(
)
:
raise
ValidationError
(
'This username is already taken.'
)
def
validate_email
(
self
,
field
)
:
if
User.
query
.
filter_by
(
=
field.
data
)
.
first
(
)
:
raise
ValidationError
(
'This email is already registered.'
)
class
LoginForm
(
FlaskForm
)
:
"""Login Form"""
username
=
StringField
(
'Username'
,
validators
=
[
DataRequired
(
message
=
'Username cannot be empty'
)
]
)
password
=
PasswordField
(
'Password'
,
validators
=
[
DataRequired
(
message
=
'Password cannot be empty'
)
]
)
remember
=
BooleanField
(
'Remember me'
)
Common Field Types
| Field Class | HTML tag | Description |
|---|---|---|
| StringField | Single-line text | |
| PasswordField | Password input | |
| EmailField | Email input | |
| TextAreaField | Multi-line text | |
| BooleanField | Checkbox | |
| SelectField | Drop-down selection |
Common Validators
| Validator | Function |
|---|---|
| DataRequired() | The field cannot be empty |
| Length(min=, max=) | Character length limit |
| Email() | Email format validation |
| EqualTo('field_name') | Match another field's value |
| Optional() | Allow the field to be empty (skip subsequent validators) |
Using Forms in View Functions
Example
File path: app/blueprints/auth.py (refactored register and login)
from
flask
import
Blueprint
,
render_template
,
redirect
,
url_for
,
flash
from
flask_login
import
login_user
,
logout_user
,
login_required
,
current_user
from
app.
forms
import
RegisterForm
,
LoginForm
from
app.
models
import
User
,
db
auth_bp
=
Blueprint
(
'auth'
,
name
)
@
auth_bp.
route
(
"/register"
,
methods
=
[
'GET'
,
'POST'
]
)
def
register
(
)
:
if
current_user.
is_authenticated
:
return
redirect
(
url_for
(
'main.index'
)
)
form
=
RegisterForm
(
)
form.validate_on_submit() validates the form on POST requests
Returns False on a GET request or validation failure
if
form.
validate_on_submit
(
)
:
user
=
User
(
username
=
form.
username
.
data
,
=
form.
.
data
)
user
.
set_password
(
form.
password
.
data
)
db.
session
.
add
(
user
)
db.
session
.
commit
(
)
login_user
(
user
)
flash
(
f
'Registration successful, welcome, {user.username}!'
,
'success'
)
return
redirect
(
url_for
(
'main.index'
)
)
On a GET request or validation failure, render the template with the form
return
render_template
(
'register.html'
,
form
=
form
)
@
auth_bp.
route
(
"/login"
,
methods
=
[
'GET'
,
'POST'
]
)
def
login
(
)
:
if
current_user.
is_authenticated
:
return
redirect
(
url_for
(
'main.index'
)
)
form
=
LoginForm
(
)
if
form.
validate_on_submit
(
)
:
user
=
User.
query
.
filter_by
(
username
=
form.
username
.
data
)
.
first
(
)
if
user
is
None
or
not
user
.
check_password
(
form.
password
.
data
)
:
flash
(
'Incorrect username or password.'
,
'error'
)
return
render_template
(
'login.html'
,
form
=
form
)
login_user
(
user
,
remember
=
form.
remember
.
data
)
flash
(
f
'Welcome back, {user.username}!'
,
'success'
)
next_page
=
request.
args
.
get
(
'next'
)
return
redirect
(
next_page
or
url_for
(
'main.index'
)
)
return
render_template
(
'login.html'
,
form
=
form
)
Rendering Forms in Templates
Example
{% extends 'base.html' %}
{% block title %}Register - RUNOOB Blog{% endblock %}
{% block content %}
Register