Last modified: Jun 01, 2025 By Alexander Williams
Install Flask-WTF in Python Easily
Flask-WTF simplifies form handling in Flask applications. It integrates WTForms with Flask for secure form processing. This guide covers installation and basic usage.
What Is Flask-WTF?
Flask-WTF is a Flask extension for working with web forms. It provides CSRF protection and file upload support. It works seamlessly with WTForms.
The extension helps validate form data easily. It also supports internationalization (i18n). For i18n, you may need Babel.
Prerequisites
Before installing Flask-WTF, ensure you have:
- Python 3.6 or higher
- Flask installed
- Virtual environment (recommended)
If you need user authentication, consider Flask-Login too.
Install Flask-WTF
Use pip to install Flask-WTF. Run this command in your terminal:
pip install Flask-WTF
This installs Flask-WTF and its dependencies. Verify installation with:
pip show Flask-WTF
Basic Flask-WTF Example
Here's a simple form example. Create a file named app.py
:
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():
name = form.name.data
return f'Hello, {name}!'
return render_template('index.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
The SECRET_KEY
is essential for CSRF protection. Never expose it in production.
Create a Template
Make a templates folder. Create index.html
inside it:
<form method="POST">
{{ form.hidden_tag() }}
{{ form.name.label }} {{ form.name() }}
{{ form.submit() }}
</form>
This renders the form with CSRF token. The token protects against cross-site request forgery.
Form Validation
Flask-WTF makes validation easy. 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 isn't empty. Other validators include Email
and Length
.
File Uploads
Flask-WTF supports file uploads. Use FileField
:
from flask_wtf.file import FileField, FileRequired
class UploadForm(FlaskForm):
file = FileField('File', validators=[FileRequired()])
submit = SubmitField('Upload')
Remember to set enctype="multipart/form-data"
in your HTML form.
Conclusion
Flask-WTF simplifies form handling in Flask applications. It provides security features like CSRF protection out of the box.
For database migrations in Flask, check Flask-Migrate. For sending emails, see Flask-Mail.
Start using Flask-WTF today to build secure forms in your Flask projects. The integration with WTForms makes it powerful yet simple to use.