WTForms-JSON
WTForms-JSON extends WTForms to provide convenient serialization and deserialization of form data to and from JSON, particularly useful for RESTful APIs. It allows forms to be populated directly from JSON payloads and validates them as usual. The latest version is 0.3.5, released in 2017. The project appears to be unmaintained.
Warnings
- breaking WTForms-JSON has not been updated since 2017 and was last tested with WTForms 2.1. It is highly likely to have compatibility issues with modern WTForms 3.x+ and newer Python versions (3.8+).
- gotcha The project is unmaintained. No new features, bug fixes, or security patches are expected. Relying on this library for new development is not recommended.
- gotcha To enable JSON processing for all WTForms forms, `wtforms_json.init_app()` must be called once at the start of your application. Failing to do so will mean forms do not gain the `.from_json()` method.
- gotcha Error messages and validation behavior for JSON input might be less configurable or user-friendly compared to contemporary libraries or custom implementations.
Install
-
pip install wtforms-json
Imports
- init_app
from wtforms_json import init_app
Quickstart
from wtforms import Form, StringField, IntegerField
from wtforms.validators import DataRequired, NumberRange
from wtforms_json import init_app
# Initialize wtforms-json to extend WTForms functionality
init_app()
class UserProfileForm(Form):
name = StringField('Name', validators=[DataRequired()])
age = IntegerField('Age', validators=[NumberRange(min=0, max=120)])
# Example JSON data (e.g., from a request body)
valid_json_data = {'name': 'Jane Doe', 'age': 25}
invalid_json_data = {'name': '', 'age': 150} # Name missing, age out of range
print("--- Processing valid data ---")
form_valid = UserProfileForm()
form_valid.from_json(valid_json_data) # Populate form from JSON
if form_valid.validate():
print(f"Form is valid. Data: {form_valid.data}")
else:
print(f"Form errors: {form_valid.errors}")
print("\n--- Processing invalid data ---")
form_invalid = UserProfileForm()
form_invalid.from_json(invalid_json_data)
if form_invalid.validate():
print(f"Form is valid. Data: {form_invalid.data}")
else:
print(f"Form errors: {form_invalid.errors}")