Flask-WTF is a popular Flask extension that provides support for working with forms in Flask. It makes it easier to create and process forms, and provides built-in functionality for form validation and security. In this article, we’ll cover the basics of building forms with Flask-WTF, including how to install Flask-WTF, create forms, and process form submissions.
Installing Flask-WTF
To use Flask-WTF in your Flask application, you’ll need to install the Flask-WTF library using pip:
pip install flask-wtf
Once you have installed Flask-WTF, you’ll need to configure it in your Flask application. Here’s an example:
from flask import Flask
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret-key'
class Form(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
submit = SubmitField('Submit')
In the code above, we first imported the Flask, Flask-WTF, and WTForms libraries. Then we created a new Flask application and defined the SECRET_KEY
configuration setting, which is used to secure form submissions.
Next, we created a Form
class that inherits from FlaskForm
. This class defines the fields in our form and the validators that should be applied to each field. In this example, we’ve created a StringField
for the name and a SubmitField
for the submit button. We’ve also added a DataRequired
validator to the name field, which ensures that the field must be filled in before the form can be submitted.
Creating Forms in Flask
Once you’ve installed and configured Flask-WTF, you can start creating forms in your Flask application. To create a form, you’ll need to render the form template and pass the form object to the template. Here’s an example:
from flask import Flask, render_template, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret-key'
class Form(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
submit = SubmitField('Submit')
@app.route('/', methods=['GET', 'POST'])
def index():
form = Form()
if form.validate_on_submit():
# Perform desired actions with the form data
return redirect(url_for('index'))
return render_template('form.html', form=form)
In the code above, we’ve created a route that handles both GET
and POST
requests to the root URL of the application. When the route is called with a GET
request, we create a new Form
object and render the form template, passing the form object to the template as a variable. When the route is called with a POST
request, we use the form.validate_on_submit
method to validate the form data.