Form validation and rendering for Python web development.
npx @tessl/cli install tessl/pypi-wtforms@3.2.0A flexible forms validation and rendering library for Python web development that works with any web framework and template engine. WTForms provides comprehensive form field types, robust data validation with built-in and custom validators, CSRF protection, internationalization support, and extensive customization options for form rendering and styling.
pip install WTFormspip install WTForms[email] for email validationimport wtformsCommon usage patterns:
from wtforms import Form, StringField, IntegerField, BooleanField
from wtforms import validators
from wtforms.fields import SelectField, DateTimeField, FieldList
from wtforms.widgets import TextArea, Selectfrom wtforms import Form, StringField, IntegerField, BooleanField, validators
class UserForm(Form):
username = StringField('Username', [
validators.DataRequired(),
validators.Length(min=4, max=25)
])
email = StringField('Email', [
validators.DataRequired(),
validators.Email()
])
age = IntegerField('Age', [
validators.NumberRange(min=13, max=120)
])
agree_terms = BooleanField('I agree to the terms')
# Process form data
form = UserForm(formdata=request.form)
if form.validate():
# Form is valid, process data
user = User(
username=form.username.data,
email=form.email.data,
age=form.age.data
)
# Save user...
else:
# Display form errors
for field, errors in form.errors.items():
for error in errors:
print(f"{field}: {error}")WTForms follows a declarative approach with several key components:
This design enables WTForms to integrate seamlessly with any Python web framework (Flask, Django, FastAPI, etc.) while providing maximum flexibility for customization and extension.
Core form functionality including form definition, data processing, validation, and object population. These are the fundamental building blocks for all form handling.
class Form:
def __init__(self, formdata=None, obj=None, prefix="", data=None, meta=None, **kwargs): ...
def validate(self, extra_validators=None) -> bool: ...
def populate_obj(self, obj): ...
def process(self, formdata=None, obj=None, data=None, extra_filters=None, **kwargs): ...
class BaseForm:
def __init__(self, fields, prefix="", meta=None): ...Comprehensive collection of form field types for handling different data types including text, numbers, dates, choices, files, and complex nested structures.
# Text and String Fields
class StringField(Field): ...
class TextAreaField(Field): ...
class PasswordField(Field): ...
class HiddenField(Field): ...
# Numeric Fields
class IntegerField(Field): ...
class FloatField(Field): ...
class DecimalField(Field): ...
# Boolean and Choice Fields
class BooleanField(Field): ...
class SelectField(Field): ...
class RadioField(Field): ...
# Date and Time Fields
class DateTimeField(Field): ...
class DateField(Field): ...
class TimeField(Field): ...Robust validation framework with built-in validators for common use cases and support for custom validation logic. Includes data requirements, length constraints, format validation, and cross-field comparisons.
class DataRequired: ...
class Length: ...
class Email: ...
class URL: ...
class NumberRange: ...
class EqualTo: ...
class Regexp: ...
class ValidationError(ValueError): ...HTML rendering system with customizable widgets for different input types, from basic text inputs to complex multi-select components and custom layouts.
class TextInput: ...
class Select: ...
class CheckboxInput: ...
class FileInput: ...
class ListWidget: ...
class TableWidget: ...
def html_params(**kwargs) -> str: ...Built-in cross-site request forgery protection with session-based token generation and validation, configurable through form meta options.
class SessionCSRF:
def __init__(self, secret_key, timeout=None): ...
def generate_csrf_token(self, csrf_token_field): ...
def validate_csrf_token(self, form, field): ...
class CSRFTokenField(HiddenField): ...Multi-language support with built-in message translations and customizable translation backends for form labels, validation messages, and error text.
def get_translations(languages=None) -> object: ...
def get_builtin_gnu_translations(languages=None) -> object: ...
class DefaultTranslations:
def gettext(self, string): ...
def ngettext(self, singular, plural, n): ...class DefaultMeta:
csrf = False
csrf_field_name = "csrf_token"
csrf_secret = None
csrf_context = None
csrf_class = None
locales = False
cache_translations = True
def bind_field(self, form, unbound_field, options): ...
def render_field(self, field, render_kw): ...
def get_translations(self, form): ...class MyForm(Form):
class Meta:
csrf = True
csrf_secret = b'your-secret-key'
locales = ['en_US', 'es_ES']
# Form fields...WTForms provides structured error handling through validation exceptions and form error collection:
try:
if form.validate():
# Process valid form
pass
else:
# Handle validation errors
for field_name, errors in form.errors.items():
for error in errors:
print(f"{field_name}: {error}")
except ValidationError as e:
# Handle specific validation exceptions
print(f"Validation failed: {e}")class Field:
"""Base class for all form fields."""
def __init__(self, label=None, validators=None, filters=(),
description="", id=None, default=None, widget=None,
render_kw=None, name=None, _form=None, _prefix="",
_translations=None, _meta=None): ...
def validate(self, form, extra_validators=()) -> bool: ...
def process(self, formdata, data=None, extra_filters=None): ...
def populate_obj(self, obj, name): ...
def __call__(self, **kwargs) -> str: ... # Render HTML
# Properties
data: any # Processed field value
raw_data: list # Raw input data
errors: list # Validation errors
label: Label # Field label object
flags: Flags # Widget flags
validators: tuple # Validator instances
class UnboundField:
"""Unbound field for class-level field definitions."""
def __init__(self, field_class, *args, **kwargs): ...
def bind(self, name, form, **kwargs) -> Field: ...
class Label:
"""HTML form label wrapper."""
def __init__(self, field_id, text): ...
def __call__(self, text=None, **kwargs) -> str: ... # Render label HTML
class Flags:
"""Container for field flags/attributes."""
def __getattr__(self, name): ...
def __setattr__(self, name, value): ...
class UnsetValue:
"""
An unset value sentinel distinct from None.
Used when None is a valid value but you need to represent unset.
"""
def __str__(self) -> str: ...
def __repr__(self) -> str: ...