WTForms

3.2.1 · active · verified Sun Apr 05

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

Install

Imports

Quickstart

Defines a simple login form with username, password, and submit fields, including basic length and data required validators. It then demonstrates instantiating the form with mock data and performing validation. For web frameworks, you would typically pass `request.form` or `request.json` to the form constructor.

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}")

view raw JSON →