Flask-WTF for Form Handling and Validation

Flask-WTF for Form Handling and Validation

Flask-WTF reads its settings from the Flask application configuration. Set SECRET_KEY before initializing the extension; Flask-WTF uses it to sign security tokens. Load the key from the environment rather than embedding a production secret in source code.

import os

from flask import Flask
from flask_wtf.csrf import CSRFProtect

csrf = CSRFProtect()


def create_app():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = os.environ["SECRET_KEY"]

    csrf.init_app(app)
    return app

Creating the extension at module scope and calling init_app inside the application factory keeps configuration tied to the app instance. It also lets tests create separate app instances with different settings.

For a small application without an app factory, initialize it directly after setting the configuration:

from flask import Flask
from flask_wtf.csrf import CSRFProtect

app = Flask(__name__)
app.config["SECRET_KEY"] = "load-this-from-a-secure-source"
csrf = CSRFProtect(app)

Use a stable, unpredictable secret in production. Rotating it invalidates tokens signed with the previous value, so users may need to reload forms they already have open. Don’t disable CSRF protection to work around a missing configuration value; fix the key configuration instead.

Defining forms with fields and validators

A form is a Python class whose fields define both the submitted data and the checks applied to it. Subclass FlaskForm, then declare each field with its widget type and validators. Keep the field names aligned with the names your application expects in the request.

from flask_wtf import FlaskForm
from wtforms import (
    BooleanField,
    PasswordField,
    StringField,
    SubmitField,
)
from wtforms.validators import (
    DataRequired,
    Email,
    EqualTo,
    Length,
)


class RegistrationForm(FlaskForm):
    username = StringField(
        "Username",
        validators=[
            DataRequired(),
            Length(min=3, max=32),
        ],
    )
    email = StringField(
        "Email",
        validators=[
            DataRequired(),
            Email(),
        ],
    )
    password = PasswordField(
        "Password",
        validators=[
            DataRequired(),
            Length(min=12, max=128),
        ],
    )
    confirm_password = PasswordField(
        "Confirm password",
        validators=[
            DataRequired(),
            EqualTo("password", message="Passwords must match."),
        ],
    )
    accept_terms = BooleanField(
        "I accept the terms",
        validators=[DataRequired()],
    )
    submit = SubmitField("Create account")

Field constructors take a label first, followed by keyword arguments such as validators. A validator is a callable that receives the field and raises a validation error when its condition fails. WTForms runs the validators in order, so put checks that establish basic presence before checks that depend on a value.

DataRequired rejects missing and empty input, and also treats values such as whitespace-only strings as empty. For fields where zero is a valid value, use InputRequired instead: it checks that input was supplied without rejecting a value merely because it evaluates to false.

Validators can express constraints directly in the form definition, keeping the rules next to the fields they govern. For example, NumberRange bounds a numeric value, while Optional permits an empty field and skips the remaining validators for it.

from flask_wtf import FlaskForm
from wtforms import IntegerField, StringField
from wtforms.validators import (
    InputRequired,
    Length,
    NumberRange,
    Optional,
)


class SearchForm(FlaskForm):
    query = StringField(
        "Search",
        validators=[
            Optional(),
            Length(max=120),
        ],
    )
    page = IntegerField(
        "Page",
        default=1,
        validators=[
            InputRequired(),
            NumberRange(min=1, max=500),
        ],
    )

For fixed choices, declare the allowed values explicitly. Each choice is a pair: the first item is the value submitted by the browser, and the second is the label presented to the user. When choices depend on database state or the current user, populate them before validating the form.

from flask_wtf import FlaskForm
from wtforms import SelectField
from wtforms.validators import DataRequired


class TicketForm(FlaskForm):
    category = SelectField(
        "Category",
        choices=[
            ("bug", "Bug report"),
            ("question", "Question"),
            ("other", "Other"),
        ],
        validators=[DataRequired()],
    )

Client-side attributes such as HTML input types and maximum lengths improve the browser interface, but they do not replace server-side validators. Treat every submitted value as untrusted, and encode the actual acceptance rules in the form class or in application logic that runs after form validation.

Rendering forms in Jinja templates

WTForms fields are callable in Jinja. Calling a field renders its widget, usually as an HTML input, and passing keyword arguments adds HTML attributes. Render the label separately so it’s associated with the input:

<form method="post" action="{{ url_for('register') }}">
  {{ form.hidden_tag() }}

  <div>
    {{ form.username.label }}
    {{ form.username(autocomplete="username", class_="text-input") }}
  </div>

  <div>
    {{ form.email.label }}
    {{ form.email(type="email", autocomplete="email") }}
  </div>

  <div>
    {{ form.password.label }}
    {{ form.password(autocomplete="new-password") }}
  </div>

  <div>
    {{ form.confirm_password.label }}
    {{ form.confirm_password(autocomplete="new-password") }}
  </div>

  <div>
    {{ form.accept_terms() }}
    {{ form.accept_terms.label }}
  </div>

  {{ form.submit() }}
</form>

Jinja’s autoescaping protects text rendered into HTML, including field labels and validation messages. Keep it enabled, and pass ordinary strings to widgets rather than marking user-controlled values as safe. WTForms uses class_ for the HTML class attribute because class is a Python keyword.

Validation errors are stored on each field as a list. Render them beside the corresponding control, where the user can identify which value needs attention:

<div>
  {{ form.email.label }}
  {{ form.email(type="email", autocomplete="email") }}

  {% for error in form.email.errors %}
    <p class="field-error">{{ error }}</p>
  {% endfor %}
</div>

A reusable macro keeps this pattern consistent across fields. The macro can accept widget attributes as keyword arguments, which lets each form control retain its own input type or autocomplete hint:

{% macro render_field(field) %}
  <div class="form-field{% if field.errors %} has-error{% endif %}">
    {{ field.label }}
    {{ field(**kwargs) }}

    {% if field.errors %}
      <ul class="field-errors">
        {% for error in field.errors %}
          <li>{{ error }}</li>
        {% endfor %}
      </ul>
    {% endif %}
  </div>
{% endmacro %}

After importing the macro, render fields without duplicating the error loop. Checkboxes often need different markup because their label is commonly placed after the input:

{% from "_form_helpers.html" import render_field %}

<form method="post">
  {{ form.hidden_tag() }}

  {{ render_field(form.username, autocomplete="username") }}
  {{ render_field(form.email, type="email", autocomplete="email") }}
  {{ render_field(form.password, autocomplete="new-password") }}
  {{ render_field(form.confirm_password, autocomplete="new-password") }}

  <div class="form-field">
    {{ form.accept_terms() }}
    {{ form.accept_terms.label }}
    {% for error in form.accept_terms.errors %}
      <p class="field-error">{{ error }}</p>
    {% endfor %}
  </div>

  {{ form.submit() }}
</form>

hidden_tag() renders the form’s hidden fields along with visible controls. For forms with hidden values that need explicit placement, render those fields individually instead. Keep the template focused on presentation: field definitions and validators belong in the form class, while the view decides whether the submitted form is valid.

Processing submissions and handling validation errors

A form object binds request data to its fields, converts values to their Python types, and runs the validators declared on those fields. In a view, validate_on_submit() is the usual gate: it returns true only for a submitted request whose fields validate. On a GET request, it returns false without treating an empty form as a failed submission.

from flask import redirect, render_template, url_for

from . import app
from .forms import RegistrationForm
from .models import User, db


@app.route("/register", methods=["GET", "POST"])
def register():
    form = RegistrationForm()

    if form.validate_on_submit():
        user = User(
            username=form.username.data,
            email=form.email.data,
        )
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        return redirect(url_for("login"))

    return render_template("register.html", form=form)

Read validated values from form.field.data, not directly from request.form. WTForms has already applied its field processing and validators, so values such as integers arrive in their converted form. Validation does not make every value safe for every use: continue to use parameterized database operations, and apply context-appropriate escaping when rendering data.

Returning the form template after an invalid POST preserves the submitted values and the errors attached to each field. A template can show both field-level errors and form-level errors:

{% if form.errors %}
  <ul class="form-errors">
    {% for field_name, errors in form.errors.items() %}
      {% for error in errors %}
        <li>{{ error }}</li>
      {% endfor %}
    {% endfor %}
  </ul>
{% endif %}

<form method="post">
  {{ form.hidden_tag() }}

  {{ form.username.label }}
  {{ form.username(autocomplete="username") }}
  {% for error in form.username.errors %}
    <p class="field-error">{{ error }}</p>
  {% endfor %}

  {{ form.email.label }}
  {{ form.email(type="email", autocomplete="email") }}
  {% for error in form.email.errors %}
    <p class="field-error">{{ error }}</p>
  {% endfor %}

  {{ form.submit() }}
</form>

The key in form.errors is a field name, and its value is a list of messages. A form-level error may use a key that does not correspond to a visible field, so iterating over the complete mapping is useful for a general error list. For a targeted display, use each field’s own errors list.

For more control over the request flow, check the method explicitly and call validate(). This is useful when GET requests need different initialization or when validation is only one step in a larger workflow:

from flask import request


@app.route("/settings", methods=["GET", "POST"])
def settings():
    form = SettingsForm()

    if request.method == "POST":
        if form.validate():
            save_settings(form)
            return redirect(url_for("settings"))

    return render_template("settings.html", form=form)

Validation errors are not exceptions in the normal view flow; validate() returns false and records messages on the form. A custom validator may raise ValidationError to add a message, while unexpected exceptions should be handled as application failures rather than converted into ordinary field errors.

Database constraints and concurrent requests still matter after form validation. For example, a validator can check whether a username is available, but another request may claim that username before the insert commits. Enforce uniqueness in the database as well, then catch the specific integrity error and return a useful response without exposing database details.

from sqlalchemy.exc import IntegrityError


@app.route("/register", methods=["GET", "POST"])
def register():
    form = RegistrationForm()

    if form.validate_on_submit():
        user = User(
            username=form.username.data,
            email=form.email.data,
        )
        user.set_password(form.password.data)
        db.session.add(user)

        try:
            db.session.commit()
        except IntegrityError:
            db.session.rollback()
            form.username.errors.append(
                "That username is no longer available."
            )
            return render_template("register.html", form=form), 409

        return redirect(url_for("login"))

    return render_template("register.html", form=form)

Protecting forms with CSRF tokens

CSRF protection prevents a browser from silently submitting an authenticated user’s cookies to an endpoint the user did not intend to invoke. Flask-WTF adds a signed token to FlaskForm instances and checks it when the form is submitted. Include the hidden fields in every form that sends a state-changing request:

<form method="post" action="{{ url_for('update_profile') }}">
  {{ form.hidden_tag() }}

  {{ form.display_name.label }}
  {{ form.display_name() }}

  {{ form.submit() }}
</form>

hidden_tag() renders the CSRF token field along with any other hidden fields. If you render hidden fields individually, include form.csrf_token. A missing, altered, or expired token makes validation fail; check validate_on_submit() as usual and render the form again with its errors.

To protect unsafe requests that do not use a FlaskForm, initialize CSRFProtect for the application. It checks tokens on methods such as POST, PUT, PATCH, and DELETE, including requests handled by ordinary Flask views.

from flask_wtf.csrf import CSRFProtect

csrf = CSRFProtect()


def create_app():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = load_secret_key()
    csrf.init_app(app)
    return app

For JavaScript requests, send the token in a request header. The default accepted header is X-CSRFToken. Render the token into the page, then attach it to requests that change server state:

<meta name="csrf-token" content="{{ csrf_token() }}">
const token = document
  .querySelector('meta[name="csrf-token"]')
  .getAttribute("content");

fetch("/api/profile", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "X-CSRFToken": token
  },
  body: JSON.stringify({ display_name: "Ada" })
});

Keep token handling separate from authorization. A valid CSRF token indicates that the request came through a page able to obtain the token; it does not prove that the current user may perform the requested operation. Check authentication and permissions in the view as well.

When token validation fails, Flask-WTF raises CSRFError before the view processes the request. An error handler can return a clear response without exposing internal details:

from flask import render_template
from flask_wtf.csrf import CSRFError


@app.errorhandler(CSRFError)
def handle_csrf_error(error):
    return render_template(
        "csrf_error.html",
        reason=error.description,
    ), 400

Do not exempt ordinary browser-facing state-changing routes just to suppress token errors. If a route genuinely uses a different authentication model and does not rely on browser cookies, exempt only that specific view rather than disabling protection application-wide:

@csrf.exempt
@app.route("/webhook", methods=["POST"])
def webhook():
    verify_webhook_signature(request)
    process_webhook(request)
    return "", 204

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *