WTForms
WTForms is a flexible forms validation and rendering library for Python web development, providing tools for data validation, CSRF protection, and internationalization. It is designed to be framework-agnostic, working with various web frameworks and template engines. It is actively maintained with regular releases.
Warnings
- breaking The `wtforms.ext.*` modules were completely removed in WTForms 3.0. These extensions (e.g., `wtforms.ext.sqlalchemy`, `wtforms.ext.appengine`, `wtforms.ext.csrf`) are now maintained as separate, independent packages (e.g., `WTForms-SQLAlchemy`, `WTForms-Appengine`, `Flask-WTF` for Flask integration with CSRF built-in).
- breaking The `wtforms.validators.Required` validator was renamed to `wtforms.validators.DataRequired` in WTForms 2.0 to clarify its behavior (checks for non-empty data).
- breaking The `TextField` alias for `StringField` was deprecated in WTForms 2.x and removed in 3.x.
- breaking In WTForms 3.2.0, the key used for form-level errors (not specific to a field) moved from `None` to an empty string `""`.
- gotcha WTForms provides the `FileField` for file input but does not handle the actual file upload storage or processing. This is typically managed by the underlying web framework (e.g., Flask's `request.files`, Django's `request.FILES`).
- gotcha WTForms handles CSRF protection directly within the core library since version 2.0, moving it out of `wtforms.ext.csrf`. If integrating with frameworks like Flask, companion libraries such as `Flask-WTF` often provide a more streamlined, automated CSRF implementation.
Install
-
pip install WTForms
Imports
- Form
from wtforms import Form
- StringField
from wtforms import StringField
- SubmitField
from wtforms import SubmitField
- validators
from wtforms import validators
- DataRequired
from wtforms.validators import DataRequired
Quickstart
from wtforms import Form, StringField, PasswordField, validators, SubmitField
class LoginForm(Form):
username = StringField('Username', [validators.Length(min=4, max=25), validators.DataRequired()])
password = PasswordField('Password', [validators.DataRequired(), validators.Length(min=8)])
submit = SubmitField('Sign In')
# Example usage (simulating a request)
if __name__ == '__main__':
# Simulate form data from a POST request
mock_form_data = {
'username': 'testuser',
'password': 'securepassword',
'submit': 'Sign In'
}
form = LoginForm(data=mock_form_data)
if form.validate():
print(f"Form validated successfully for user: {form.username.data}")
# In a real application, you'd process the data here
else:
print("Form validation failed:")
for field, errors in form.errors.items():
for error in errors:
print(f" {field}: {error}")
# Example with invalid data
invalid_form_data = {
'username': 'abc',
'password': 'short',
'submit': 'Sign In'
}
invalid_form = LoginForm(data=invalid_form_data)
if not invalid_form.validate():
print("\nInvalid form submitted:")
for field, errors in invalid_form.errors.items():
for error in errors:
print(f" {field}: {error}")