Using Flask-WTF
Introduction to Flask-WTF
Flask-WTF is an extension for Flask that integrates the power of Flask and WTForms, which makes form handling in Flask easy and straightforward. In this article, we will discuss how to use Flask-WTF to create and validate forms in your Flask applications.
Installation of Flask-WTF
Before we can start using Flask-WTF, we have to install it. If you have pip installed, you can simply use the following command in your terminal to install Flask-WTF:
pip install flask-wtf
Creating a Simple Form with Flask-WTF
To start with, let's create a simple form with Flask-WTF. First, we need to import FlaskForm
from flask_wtf
and StringField
, PasswordField
and SubmitField
from wtforms
. Then we can define our form as a class:
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
class LoginForm(FlaskForm):
username = StringField('Username')
password = PasswordField('Password')
submit = SubmitField('Log In')
In this example, we created a simple login form with a username field, a password field, and a submit button.
Rendering the Form in a Template
After creating the form, we will need to render it in a template. In Flask, we typically use Jinja2 templates. Here is a simple example of how to render the form in a template:
<form method="POST">
{{ form.hidden_tag() }}
{{ form.username.label }} {{ form.username() }}
{{ form.password.label }} {{ form.password() }}
{{ form.submit() }}
</form>
In this example, form.hidden_tag()
generates a hidden CSRF token field. form.username.label
and form.username()
generate the label and the input field for the username, respectively. The same goes for the password field and the submit button.
Handling Form Submission in a View
Now that we have our form and our template, we need to handle the form submission in a view. Here is a simple example of how to do this:
from flask import Flask, render_template, request
from .forms import LoginForm
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
# handle the form submission
pass
return render_template('login.html', form=form)
In this example, we first create an instance of our LoginForm
. Then, if the form is submitted (request.method == 'POST'
) and all form data is valid (form.validate()
), we handle the form submission. Otherwise, we render the template with the form.
Form Validation with Flask-WTF
Flask-WTF also provides an easy way to validate form data. For example, to ensure that the username and the password are not empty, we can use the DataRequired
validator:
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
submit = SubmitField('Log In')
In this example, if the username or the password is empty, form.validate_on_submit()
will return False
, and an error message will be attached to the corresponding field.
In conclusion, Flask-WTF makes form handling in Flask easy and straightforward. With just a few lines of code, you can create forms, validate form data, and handle form submissions. Happy coding!