Flask-WTF
Forms are not only about display (i.e. HTML forms), forms are about validation.
We will be building a registration form, and the best form library for Flask is Flask-WTF which is built on top of an older package called WTForms. The following code will actually install both:
pip install flask-wtf
This package also provides us with CSRF protection (i.e. Cross-Site Request Forgery). This will prevent fake requests from communicating with the app server, using a one-time code, if the form doesn’t have that code the request is ignored.
[forms.py]
from flask_wtf import Form from wtforms import StringField, PasswordField from wtforms.validators import DataRequired, Regexp, ValidationError, Email, Length, EqualTo from models import User def name_exists(form, field): if User.select().where(User.username == field.data ).exists(): raise ValidationError('User with that name already exists!') def email_exists(form, field): if User.select().where(User.email == field.data ).exists(): raise ValidationError('User with that email already exists!') class RegisterForm(Form): username = StringField( 'Username', validators = [ DataRequired(), Regexp( r'^[a-zA-Z0-9_]+$', message="Only letters, numbers and underscores are allowed." ), name_exists ]) email = StringField( 'Email', validators = [ DataRequired(), Email(), email_exists ]) password = PasswordField( 'Password', validators = [ DataRequired(), Length(min=2), EqualTo('password2', message='Passwords must match!') ]) password2 = PasswordField( 'Confirm Password', validators = [DataRequired()] )
WTForms Fields
StringField( Placeholder Label, Validators List )
PasswordField( Placeholder Label, Validators List )
WTForms Validators
DataRequired, Regexp, ValidationError, Email, Length, EqualTo
def name_exists(form, field):
Any function passed into the validators should have form and field arguments, which are passed through the app file (e.g. the register view).
field.data
Gets data from the corresponding field.
.exists( )
Returns a Boolean value after checking the database.
r’^[a-zA-Z0-9_]+$’
Regular Expression, it starts, is one word that contains characters from a-z or A-Z or 0-9 or _, as many as user wants, but at least one.