Last modified: Jun 11, 2025 By Alexander Williams
Install Flask-WTF in Python - Quick Guide
Flask-WTF is a Flask extension for handling web forms. It integrates WTForms with Flask, making form creation and validation easy. This guide will show you how to install and use Flask-WTF.
What is Flask-WTF?
Flask-WTF simplifies form handling in Flask applications. It provides CSRF protection, file uploads, and validation. It works seamlessly with WTForms.
Prerequisites
Before installing Flask-WTF, ensure you have Python and Flask installed. If not, install Flask first.
pip install Flask
Install Flask-WTF
Use pip
to install Flask-WTF. Run the following command in your terminal.
pip install Flask-WTF
This will download and install Flask-WTF and its dependencies.
Verify Installation
Check if Flask-WTF is installed correctly. Run the following Python code.
import flask_wtf
print(flask_wtf.__version__)
If installed correctly, it will print the version number.
Basic Flask-WTF Example
Here’s a simple example to create a form using Flask-WTF.
from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
class MyForm(FlaskForm):
name = StringField('Name')
submit = SubmitField('Submit')
@app.route('/', methods=['GET', 'POST'])
def index():
form = MyForm()
if form.validate_on_submit():
return f'Hello, {form.name.data}!'
return render_template('index.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
This code creates a form with a name field and a submit button.
Create a Template
Create an index.html
file in a templates
folder.
<form method="POST">
{{ form.hidden_tag() }}
{{ form.name.label }} {{ form.name() }}
{{ form.submit() }}
</form>
This template renders the form fields.
Run the Application
Start the Flask application.
python app.py
Open your browser and go to http://localhost:5000
to see the form.
Form Validation
Flask-WTF provides built-in validation. Add validators to your form fields.
from wtforms.validators import DataRequired
class MyForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
submit = SubmitField('Submit')
The DataRequired
validator ensures the field is not empty.
CSRF Protection
Flask-WTF includes CSRF protection. Always include {{ form.hidden_tag() }}
in your templates.
Conclusion
Flask-WTF makes form handling in Flask easy and secure. It integrates well with WTForms and provides useful features like validation and CSRF protection. For more Flask extensions, check out our guide on How to Install Flask-Migrate in Python.
If you need to handle emails in Flask, read our Install Flask-Mail in Python - Quick Guide. For timezone handling, see How to Install pytz in Python - Quick Guide.