[starlette-wtf] The StarletteForm Class
0
Contents
Starlette-WTF provides a form class that makes it easy to add form validation and CSRF protection to Starlette apps.
from starlette_wtf import StarletteForm
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, EqualTo
from wtforms.widgets import PasswordInput
class CreateAccountForm(StarletteForm):
email = TextField(
'Email address',
validators=[
DataRequired('Please enter your email address'),
Email()
]
)
password = PasswordField(
'Password',
widget=PasswordInput(hide_value=False),
validators=[
DataRequired('Please enter your password'),
EqualTo('password_confirm', message='Passwords must match')
]
)
password_confirm = PasswordField(
'Confirm Password',
widget=PasswordInput(hide_value=False),
validators=[
DataRequired('Please confirm your password')
]
)
Often you will want to initialize form objects using default values on GET requests and from submitted formdata on POST requests. To make this easier you can use the .from_formdata() async class method which does this for you automatically:
@app.route('/create-account', methods=['GET', 'POST'])
async def create_account(request):
"""GET|POST /create-account: Create account form handler
"""
form = await CreateAccountForm.from_formdata(request)
return PlainTextResponse()
Code example provided in the readme file of the starlette-wtf project on github.
About starlette-wtf
starlette-wtf - a simple tool for integrating Starlette and WTForms.