Flask-WTF / WTForms
Flask-WTF integrates the WTForms library into Flask to build and validate HTML forms in Python. You define a form as a class with fields and validators, and it handles rendering, validation, and CSRF protection.
Flask
Instead of writing raw <input> tags and validating by hand, you declare a FlaskForm subclass with fields like StringField and PasswordField, each carrying validators such as DataRequired() or Email(). The form object then renders fields and reports errors.
In a view you create the form, then call form.validate_on_submit(), which returns True only on a POST request whose data passes every validator. On success you read form.field.data; on failure the same template re-renders with error messages.
Flask-WTF automatically adds a hidden CSRF token to every form and verifies it on submission, protecting against cross-site request forgery as long as you render {{ form.hidden_tag() }} in the template.
Syntax
class LoginForm(FlaskForm):
email = StringField(validators=[DataRequired()])Examples
Python
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired, Email
class SignupForm(FlaskForm):
email = StringField("Email", validators=[DataRequired(), Email()])
@app.route("/signup", methods=["GET", "POST"])
def signup():
form = SignupForm()
if form.validate_on_submit():
return f"Welcome {form.email.data}"
return render_template("signup.html", form=form)