Python course ยท Module 5: Flask and Web Apps
Flask-WTF - forms and validation
In this lesson13
Welcome again! Darwin here, ready to show you professional forms with Flask-WTF!
So far you've been handling forms manually via request.form. That works, but there's no validation, no CSRF protection, and it's error-prone!
Safari Analogy: Manual form handling is like manually checking every tourist without a checklist - easy to miss something! Flask-WTF is like a professional registration form with automatic validation - everything is verified!
The problem with manual forms
@app.route('/add-species', methods=['POST'])
def add_species():
name = request.form.get('name')
population = request.form.get('population')
# No validation - what if name is empty?
# No type validation - what if population is text?
# No CSRF protection
# Must check everything manually
if not name:
return "Error: Name is required", 400
try:
population = int(population)
except ValueError:
return "Error: Population must be a number", 400
# Add to database...Problems: Long validation code No CSRF protection (Cross-Site Request Forgery) Must repeat validation for every form No automatic error display Hard to maintain
Solution - Flask-WTF
Flask-WTF is an extension integrating WTForms (forms library) with Flask.
What does Flask-WTF provide? Automatic validation - no manual checking needed CSRF protection - security out-of-the-box Form classes - readable, DRY code Template rendering - easy display Error messages - automatic display
Installing Flask-WTF
pip install Flask-WTFFlask-WTF automatically installs WTForms (core library).
Add to requirements.txt
pip freeze > requirements.txtConfiguring Flask-WTF
Flask-WTF requires a secret key for CSRF protection:
# app.py
from flask import Flask
from flask_wtf import FlaskForm
app = Flask(__name__)
# SECRET_KEY is required for CSRF protection
app.config['SECRET_KEY'] = 'your-super-secret-key-12345' # Change in production!
# Alternatively - use os.urandom()
import os
app.config['SECRET_KEY'] = os.urandom(24)IMPORTANT: In production use environment variables instead of hardcoded keys!
import os
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') or 'dev-key-123'Creating a form class
A form is a class inheriting from FlaskForm:
# forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, TextAreaField, SelectField, SubmitField
from wtforms.validators import DataRequired, Length, NumberRange, Optional
class AddSpeciesForm(FlaskForm):
name = StringField('Species name',
validators=[DataRequired(message='Name is required'),
Length(min=2, max=100, message='Name must be 2-100 characters')])
scientific_name = StringField('Scientific name',
validators=[DataRequired(),
Length(min=2, max=150)])
population = IntegerField('Population',
validators=[DataRequired(),
NumberRange(min=0, message='Population cannot be negative')])
habitat = SelectField('Habitat',
choices=[('savanna', 'Savanna'),
('forest', 'Forest'),
('desert', 'Desert'),
('wetland', 'Wetland')],
validators=[DataRequired()])
notes = TextAreaField('Notes',
validators=[Optional(), Length(max=500)])
submit = SubmitField('Add species')Form fields:
StringField- text input (input type="text")IntegerField- integer (input type="number")TextAreaField- multiline text (textarea)SelectField- dropdown list (select)SubmitField- submit button (button type="submit")
Other field types:
EmailField- email with validationPasswordField- password (input type="password")BooleanField- checkboxDateField- dateFileField- file uploadRadioField- radio buttonsDecimalField- floating point number
Validators - data validation
WTForms has built-in validators:
from wtforms.validators import (
DataRequired, # Field is required
Optional, # Field is optional
Length, # Text length
Email, # Email validation
EqualTo, # Equal to another field (passwords)
NumberRange, # Number range
Regexp, # Regex
URL, # URL validation
AnyOf, # One of values
NoneOf # None of values
)Examples:
from wtforms import StringField, IntegerField, PasswordField
from wtforms.validators import DataRequired, Length, Email, EqualTo, NumberRange
class RegistrationForm(FlaskForm):
username = StringField('Username',
validators=[DataRequired(),
Length(min=4, max=20)])
email = EmailField('Email',
validators=[DataRequired(), Email()])
password = PasswordField('Password',
validators=[DataRequired(),
Length(min=8)])
confirm_password = PasswordField('Confirm password',
validators=[DataRequired(),
EqualTo('password', message='Passwords must match')])
age = IntegerField('Age',
validators=[NumberRange(min=13, max=120,
message='Age must be between 13 and 120')])Using a form in a route
# app.py
from flask import Flask, render_template, redirect, url_for, flash
from forms import AddSpeciesForm
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key-123'
species_db = {}
next_id = 1
@app.route('/species/add', methods=['GET', 'POST'])
def add_species():
form = AddSpeciesForm()
# POST request + validation passed
if form.validate_on_submit():
global next_id
# Get data from form
new_species = {
'id': next_id,
'name': form.name.data,
'scientific_name': form.scientific_name.data,
'population': form.population.data,
'habitat': form.habitat.data,
'notes': form.notes.data
}
species_db[next_id] = new_species
next_id += 1
# Flash message - success notification
flash(f'Species {new_species["name"]} has been added!', 'success')
return redirect(url_for('list_species'))
# GET request or validation failed
return render_template('add_species.html', form=form)How it works?
- GET request โ renders the form
- POST request โ
form.validate_on_submit()checks:- Is the method POST?
- Is the CSRF token valid?
- Did all validators pass?
- If validation OK โ process data (
form.field_name.data) - If validation FAILED โ re-render the form with errors
Rendering a form in a template
{% extends 'base.html' %}
{% block title %}Add species - Safari Database{% endblock %}
{% block content %}
<h2>Add new species</h2>
<form method="POST" novalidate>
{{ form.hidden_tag() }} <!-- CSRF token -->
<div style="margin: 15px 0;">
{{ form.name.label }}
{{ form.name(size=40) }}
{% if form.name.errors %}
<ul style="color: red; margin: 5px 0;">
{% for error in form.name.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
<div style="margin: 15px 0;">
{{ form.scientific_name.label }}
{{ form.scientific_name(size=40) }}
{% if form.scientific_name.errors %}
<ul style="color: red; margin: 5px 0;">
{% for error in form.scientific_name.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
<div style="margin: 15px 0;">
{{ form.population.label }}
{{ form.population() }}
{% if form.population.errors %}
<ul style="color: red; margin: 5px 0;">
{% for error in form.population.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
<div style="margin: 15px 0;">
{{ form.habitat.label }}
{{ form.habitat() }}
{% if form.habitat.errors %}
<ul style="color: red; margin: 5px 0;">
{% for error in form.habitat.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
<div style="margin: 15px 0;">
{{ form.notes.label }}
{{ form.notes(rows=5, cols=40) }}
{% if form.notes.errors %}
<ul style="color: red; margin: 5px 0;">
{% for error in form.notes.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
<div style="margin-top: 20px;">
{{ form.submit(style='padding: 10px 20px; background: #2c5f2d; color: white; border: none; border-radius: 4px; cursor: pointer;') }}
</div>
</form>
<p style="margin-top: 20px;">
<a href="{{ url_for('list_species') }}">โ Back to list</a>
</p>
{% endblock %}Key elements:
{{ form.hidden_tag() }}- CSRF token (required!){{ form.field_name.label }}- field label{{ form.field_name() }}- form field{% if form.field_name.errors %}- display errors
Flash messages - notifications
Flask has a built-in flash messages system for displaying notifications:
from flask import flash
@app.route('/species/add', methods=['POST'])
def add_species():
form = AddSpeciesForm()
if form.validate_on_submit():
# ... add species ...
flash('Species has been added!', 'success')
return redirect(url_for('list_species'))
# Validation error
flash('Please fix the errors in the form.', 'error')
return render_template('add_species.html', form=form)Flash categories:
'success'- success (green)'error'- error (red)'warning'- warning (orange)'info'- information (blue)
Displaying flash messages in templates
In base.html add:
<!DOCTYPE html>
<html>
<head>...</head>
<body>
<header>...</header>
<!-- Flash messages -->
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<div style="max-width: 900px; margin: 20px auto;">
{% for category, message in messages %}
<div style="padding: 15px; margin: 10px 0; border-radius: 4px;
{% if category == 'success' %}background: #d4edda; color: #155724; border: 1px solid #c3e6cb;
{% elif category == 'error' %}background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb;
{% elif category == 'warning' %}background: #fff3cd; color: #856404; border: 1px solid #ffeaa7;
{% else %}background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb;{% endif %}">
{{ message }}
</div>
{% endfor %}
</div>
{% endif %}
{% endwith %}
<main>{% block content %}{% endblock %}</main>
</body>
</html>Macro for rendering fields - DRY
Instead of repeating code for each field, create a macro:
{# templates/macros.html #}
{% macro render_field(field) %}
<div style="margin: 15px 0;">
{{ field.label }}
{{ field(size=40, **kwargs) }}
{% if field.errors %}
<ul style="color: #d62828; margin: 5px 0; padding-left: 20px;">
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
{% endmacro %}
{# Usage in form #}
{% from 'macros.html' import render_field %}
<form method="POST" novalidate>
{{ form.hidden_tag() }}
{{ render_field(form.name) }}
{{ render_field(form.scientific_name) }}
{{ render_field(form.population) }}
{{ render_field(form.habitat) }}
{{ render_field(form.notes) }}
<div style="margin-top: 20px;">
{{ form.submit(style='...') }}
</div>
</form>Edit form - populating with data
# forms.py
class EditSpeciesForm(FlaskForm):
name = StringField('Name', validators=[DataRequired(), Length(min=2, max=100)])
scientific_name = StringField('Scientific name', validators=[DataRequired()])
population = IntegerField('Population', validators=[DataRequired(), NumberRange(min=0)])
habitat = SelectField('Habitat',
choices=[('savanna', 'Savanna'), ('forest', 'Forest'),
('desert', 'Desert'), ('wetland', 'Wetland')])
notes = TextAreaField('Notes', validators=[Optional(), Length(max=500)])
submit = SubmitField('Save changes')
# app.py
@app.route('/species/<int:species_id>/edit', methods=['GET', 'POST'])
def edit_species(species_id):
species = species_db.get(species_id)
if not species:
flash('Species not found.', 'error')
return redirect(url_for('list_species'))
form = EditSpeciesForm()
if form.validate_on_submit():
# Update data
species['name'] = form.name.data
species['scientific_name'] = form.scientific_name.data
species['population'] = form.population.data
species['habitat'] = form.habitat.data
species['notes'] = form.notes.data
flash(f'Species {species["name"]} has been updated!', 'success')
return redirect(url_for('show_species', species_id=species_id))
elif request.method == 'GET':
# Populate form with current data
form.name.data = species['name']
form.scientific_name.data = species['scientific_name']
form.population.data = species['population']
form.habitat.data = species['habitat']
form.notes.data = species.get('notes', '')
return render_template('edit_species.html', form=form, species=species)Logic:
- GET - populate form with database data
- POST + valid - save changes
- POST + invalid - display errors
Custom validators
You can create your own validators:
from wtforms.validators import ValidationError
class AddSpeciesForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
scientific_name = StringField('Scientific name', validators=[DataRequired()])
population = IntegerField('Population', validators=[DataRequired()])
# Custom validator - validate_<field_name> method
def validate_name(self, field):
# Check if species already exists
for species in species_db.values():
if species['name'].lower() == field.data.lower():
raise ValidationError('A species with this name already exists!')
def validate_scientific_name(self, field):
# Check scientific name format (Genus species)
parts = field.data.split()
if len(parts) != 2:
raise ValidationError('Scientific name must follow format: Genus species')
# Check if first word starts with uppercase
if not parts[0][0].isupper() or not parts[1][0].islower():
raise ValidationError('Format: first word uppercase, second lowercase')Custom validator function:
def validate_population_range(form, field):
if field.data < 10:
raise ValidationError('Population must be at least 10 individuals')
if field.data > 1000000:
raise ValidationError('Population exceeds realistic range')
class AddSpeciesForm(FlaskForm):
population = IntegerField('Population',
validators=[DataRequired(), validate_population_range])Complete example - Safari Database with forms
forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, TextAreaField, SelectField, SubmitField
from wtforms.validators import DataRequired, Length, NumberRange, Optional, ValidationError
class AddSpeciesForm(FlaskForm):
name = StringField('Species name',
validators=[DataRequired(message='Name is required'),
Length(min=2, max=100)])
scientific_name = StringField('Scientific name',
validators=[DataRequired(), Length(min=5, max=150)])
population = IntegerField('Population',
validators=[DataRequired(), NumberRange(min=0)])
habitat = SelectField('Habitat',
choices=[('savanna', 'Savanna'), ('forest', 'Forest'),
('desert', 'Desert'), ('wetland', 'Wetland')],
validators=[DataRequired()])
notes = TextAreaField('Notes', validators=[Optional(), Length(max=500)])
submit = SubmitField('Add species')
def validate_scientific_name(self, field):
parts = field.data.split()
if len(parts) < 2:
raise ValidationError('Scientific name must follow format: Genus species')app.py
from flask import Flask, render_template, redirect, url_for, flash
from forms import AddSpeciesForm
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key-here'
species_db = {
1: {'id': 1, 'name': 'Lion', 'scientific_name': 'Panthera leo',
'population': 120, 'habitat': 'savanna', 'notes': ''},
}
next_id = 2
@app.route('/')
def home():
return render_template('home.html', species_count=len(species_db))
@app.route('/species')
def list_species():
return render_template('species_list.html', species=list(species_db.values()))
@app.route('/species/add', methods=['GET', 'POST'])
def add_species():
form = AddSpeciesForm()
if form.validate_on_submit():
global next_id
new_species = {
'id': next_id,
'name': form.name.data,
'scientific_name': form.scientific_name.data,
'population': form.population.data,
'habitat': form.habitat.data,
'notes': form.notes.data
}
species_db[next_id] = new_species
next_id += 1
flash(f'Species {new_species["name"]} has been added!', 'success')
return redirect(url_for('show_species', species_id=new_species['id']))
return render_template('add_species.html', form=form)
@app.route('/species/<int:species_id>')
def show_species(species_id):
species = species_db.get(species_id)
return render_template('species_detail.html', species=species)
if __name__ == '__main__':
app.run(debug=True)Final Safari Analogy: Flask-WTF is like a professional safari registration form with automatic validation - checks tourist age (NumberRange), requires a signature (DataRequired), verifies email (Email), and protects against document forgery (CSRF)! You don't have to manually check every field!
Next lesson: Darwin will show you Flask-Login - user authentication (login, registration, route protection)!
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How do you install Flask-WTF?
2. Which class does a Flask-WTF form inherit from?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Arrange the definition of a form class in Flask-WTF:
- Click in order
Arrange the definition of a StringField with a DataRequired validator:
- Code editor
Write a SpeciesForm class with name (string, required), population (int), and submit fields.
- Horizontal ordering
How do you check if a form passed validation?