Introduction

Flask-WTF is an extension for Flask that simplifies form handling and validation in Flask applications. It integrates with the popular WTForms library to create, render, and validate forms with ease. In this guide, we'll explore how to use Flask-WTF for form handling in your Flask web application.


Step 1: Installing Flask-WTF

Before you can use Flask-WTF, you need to install it. You can install Flask-WTF using pip:

pip install Flask-WTF

Step 2: Creating a Form

Create a form class using WTForms. Here's an example of a simple form for user registration:

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email, EqualTo
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Register')

Step 3: Rendering a Form in Your Template

Render the form in your HTML template. Use the `form` variable to access the fields and render them. Here's an example:

<!DOCTYPE html>
<html>
<head>
<title>Registration</title>
</head>
<body>
<h1>Register</h1>
<form method="POST">
{{ form.hidden_tag() }}
<div>
{{ form.username.label }}
{{ form.username(size=32) }}
</div>
<div>
{{ form.email.label }}
{{ form.email(size=32) }}
</div>
<div>
{{ form.password.label }}
{{ form.password(size=32) }}
</div>
<div>
{{ form.confirm_password.label }}
{{ form.confirm_password(size=32) }}
</div>
<div>
{{ form.submit() }}
</div>
</form>
</body>
</html>

Step 4: Handling Form Submission

In your Flask route, handle form submission, validate the form data, and process it. Here's an example route for processing the registration form:

from flask import Flask, render_template, redirect, url_for, flash
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email, EqualTo
app = Flask(__name)
app.secret_key = 'your_secret_key'
# Form class definition (as shown in Step 2)
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
flash('Registration successful!', 'success')
return redirect(url_for('home'))
return render_template('registration.html', form=form)
if __name__ == '__main__':
app.run()

The form is validated using `form.validate_on_submit()`, and success or error messages can be flashed to the user.


Conclusion

Flask-WTF simplifies form handling and validation in Flask applications. By following these steps, you can create forms, render them in your templates, and process form submissions with ease. Flask-WTF integrates seamlessly with WTForms, allowing you to build robust and interactive web applications.