0
# WTForms
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: WTForms
7
- **Language**: Python
8
- **Installation**: `pip install WTForms`
9
- **Optional Dependencies**: `pip install WTForms[email]` for email validation
10
11
## Core Imports
12
13
```python
14
import wtforms
15
```
16
17
Common usage patterns:
18
19
```python
20
from wtforms import Form, StringField, IntegerField, BooleanField
21
from wtforms import validators
22
from wtforms.fields import SelectField, DateTimeField, FieldList
23
from wtforms.widgets import TextArea, Select
24
```
25
26
## Basic Usage
27
28
```python
29
from wtforms import Form, StringField, IntegerField, BooleanField, validators
30
31
class UserForm(Form):
32
username = StringField('Username', [
33
validators.DataRequired(),
34
validators.Length(min=4, max=25)
35
])
36
email = StringField('Email', [
37
validators.DataRequired(),
38
validators.Email()
39
])
40
age = IntegerField('Age', [
41
validators.NumberRange(min=13, max=120)
42
])
43
agree_terms = BooleanField('I agree to the terms')
44
45
# Process form data
46
form = UserForm(formdata=request.form)
47
if form.validate():
48
# Form is valid, process data
49
user = User(
50
username=form.username.data,
51
email=form.email.data,
52
age=form.age.data
53
)
54
# Save user...
55
else:
56
# Display form errors
57
for field, errors in form.errors.items():
58
for error in errors:
59
print(f"{field}: {error}")
60
```
61
62
## Architecture
63
64
WTForms follows a declarative approach with several key components:
65
66
- **Form Classes**: Define form structure using field declarations with metaclass support
67
- **Field Hierarchy**: Extensible field types handling data processing, validation, and rendering
68
- **Validation Chain**: Composable validators that can be combined and customized
69
- **Widget System**: Pluggable HTML rendering components for different input types
70
- **Meta Configuration**: Centralized configuration for CSRF, internationalization, and customization
71
- **CSRF Protection**: Built-in protection against cross-site request forgery attacks
72
73
This design enables WTForms to integrate seamlessly with any Python web framework (Flask, Django, FastAPI, etc.) while providing maximum flexibility for customization and extension.
74
75
## Capabilities
76
77
### Form Classes and Processing
78
79
Core form functionality including form definition, data processing, validation, and object population. These are the fundamental building blocks for all form handling.
80
81
```python { .api }
82
class Form:
83
def __init__(self, formdata=None, obj=None, prefix="", data=None, meta=None, **kwargs): ...
84
def validate(self, extra_validators=None) -> bool: ...
85
def populate_obj(self, obj): ...
86
def process(self, formdata=None, obj=None, data=None, extra_filters=None, **kwargs): ...
87
88
class BaseForm:
89
def __init__(self, fields, prefix="", meta=None): ...
90
```
91
92
[Forms and Processing](./forms.md)
93
94
### Field Types
95
96
Comprehensive collection of form field types for handling different data types including text, numbers, dates, choices, files, and complex nested structures.
97
98
```python { .api }
99
# Text and String Fields
100
class StringField(Field): ...
101
class TextAreaField(Field): ...
102
class PasswordField(Field): ...
103
class HiddenField(Field): ...
104
105
# Numeric Fields
106
class IntegerField(Field): ...
107
class FloatField(Field): ...
108
class DecimalField(Field): ...
109
110
# Boolean and Choice Fields
111
class BooleanField(Field): ...
112
class SelectField(Field): ...
113
class RadioField(Field): ...
114
115
# Date and Time Fields
116
class DateTimeField(Field): ...
117
class DateField(Field): ...
118
class TimeField(Field): ...
119
```
120
121
[Field Types](./fields.md)
122
123
### Validation System
124
125
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.
126
127
```python { .api }
128
class DataRequired: ...
129
class Length: ...
130
class Email: ...
131
class URL: ...
132
class NumberRange: ...
133
class EqualTo: ...
134
class Regexp: ...
135
class ValidationError(ValueError): ...
136
```
137
138
[Validation](./validation.md)
139
140
### Widget System and Rendering
141
142
HTML rendering system with customizable widgets for different input types, from basic text inputs to complex multi-select components and custom layouts.
143
144
```python { .api }
145
class TextInput: ...
146
class Select: ...
147
class CheckboxInput: ...
148
class FileInput: ...
149
class ListWidget: ...
150
class TableWidget: ...
151
def html_params(**kwargs) -> str: ...
152
```
153
154
[Widgets and Rendering](./widgets.md)
155
156
### CSRF Protection
157
158
Built-in cross-site request forgery protection with session-based token generation and validation, configurable through form meta options.
159
160
```python { .api }
161
class SessionCSRF:
162
def __init__(self, secret_key, timeout=None): ...
163
def generate_csrf_token(self, csrf_token_field): ...
164
def validate_csrf_token(self, form, field): ...
165
166
class CSRFTokenField(HiddenField): ...
167
```
168
169
[CSRF Protection](./csrf.md)
170
171
### Internationalization
172
173
Multi-language support with built-in message translations and customizable translation backends for form labels, validation messages, and error text.
174
175
```python { .api }
176
def get_translations(languages=None) -> object: ...
177
def get_builtin_gnu_translations(languages=None) -> object: ...
178
179
class DefaultTranslations:
180
def gettext(self, string): ...
181
def ngettext(self, singular, plural, n): ...
182
```
183
184
[Internationalization](./i18n.md)
185
186
## Advanced Configuration
187
188
### Meta Configuration
189
190
```python { .api }
191
class DefaultMeta:
192
csrf = False
193
csrf_field_name = "csrf_token"
194
csrf_secret = None
195
csrf_context = None
196
csrf_class = None
197
locales = False
198
cache_translations = True
199
200
def bind_field(self, form, unbound_field, options): ...
201
def render_field(self, field, render_kw): ...
202
def get_translations(self, form): ...
203
```
204
205
### Custom Form Meta
206
207
```python
208
class MyForm(Form):
209
class Meta:
210
csrf = True
211
csrf_secret = b'your-secret-key'
212
locales = ['en_US', 'es_ES']
213
214
# Form fields...
215
```
216
217
## Error Handling
218
219
WTForms provides structured error handling through validation exceptions and form error collection:
220
221
```python
222
try:
223
if form.validate():
224
# Process valid form
225
pass
226
else:
227
# Handle validation errors
228
for field_name, errors in form.errors.items():
229
for error in errors:
230
print(f"{field_name}: {error}")
231
except ValidationError as e:
232
# Handle specific validation exceptions
233
print(f"Validation failed: {e}")
234
```
235
236
## Types
237
238
```python { .api }
239
class Field:
240
"""Base class for all form fields."""
241
def __init__(self, label=None, validators=None, filters=(),
242
description="", id=None, default=None, widget=None,
243
render_kw=None, name=None, _form=None, _prefix="",
244
_translations=None, _meta=None): ...
245
246
def validate(self, form, extra_validators=()) -> bool: ...
247
def process(self, formdata, data=None, extra_filters=None): ...
248
def populate_obj(self, obj, name): ...
249
def __call__(self, **kwargs) -> str: ... # Render HTML
250
251
# Properties
252
data: any # Processed field value
253
raw_data: list # Raw input data
254
errors: list # Validation errors
255
label: Label # Field label object
256
flags: Flags # Widget flags
257
validators: tuple # Validator instances
258
259
class UnboundField:
260
"""Unbound field for class-level field definitions."""
261
def __init__(self, field_class, *args, **kwargs): ...
262
def bind(self, name, form, **kwargs) -> Field: ...
263
264
class Label:
265
"""HTML form label wrapper."""
266
def __init__(self, field_id, text): ...
267
def __call__(self, text=None, **kwargs) -> str: ... # Render label HTML
268
269
class Flags:
270
"""Container for field flags/attributes."""
271
def __getattr__(self, name): ...
272
def __setattr__(self, name, value): ...
273
274
class UnsetValue:
275
"""
276
An unset value sentinel distinct from None.
277
Used when None is a valid value but you need to represent unset.
278
"""
279
def __str__(self) -> str: ...
280
def __repr__(self) -> str: ...
281
```