In this tutorial, our goal is to help you understand how to use Flask-WTF, a simple integration of Flask and WTForms, to build secure web forms. You'll learn how to handle form validation, CSRF protection, and secure form submission.
By the end of this tutorial, you will be able to:
This tutorial assumes that you have a basic understanding of Python and Flask. If you are not familiar with Flask, consider reading some introductory materials or tutorials about Flask before proceeding.
Flask-WTF is a wrapper around the WTForms library that integrates it with Flask's features. It provides a simple and unified API to handle web forms in Flask applications.
To use Flask-WTF, we first need to install it. In your terminal, run:
pip install flask-wtf
Next, we create a form class that inherits from FlaskForm. Inside this class, we can define the fields we want in our form. For example:
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
class MyForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
submit = SubmitField('Submit')
In the above code, name
is a field with a label 'Name' and a validator that ensures the field is not submitted empty.
When the form is submitted, we can call the validate_on_submit()
method. This will return True
if the form was submitted and the data passed all validators.
@app.route('/', methods=['GET', 'POST'])
def index():
form = MyForm()
if form.validate_on_submit():
# form was submitted and data is valid
return 'Form successfully submitted!'
return render_template('index.html', form=form)
Let's look at a complete example of a Flask application with a secure form.
from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
class MyForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
submit = SubmitField('Submit')
@app.route('/', methods=['GET', 'POST'])
def index():
form = MyForm()
if form.validate_on_submit():
return 'Form successfully submitted!'
return render_template('index.html', form=form)
if __name__ == "__main__":
app.run(debug=True)
In this application, when the user submits the form, the server checks if the data is valid. If it is, it returns a success message.
In this tutorial, we learned how to use Flask-WTF to create secure web forms in Flask applications. We covered form creation, validation, and CSRF protection.
For further study, consider exploring more complex form fields and validators provided by WTForms, or learn how to handle file uploads with Flask-WTF.
Exercise: Create a form with more fields (e.g., email, password, etc.) and apply appropriate validators to each field.
Exercise: Implement a login form and check the submitted password against a hardcoded password.
Exercise: Render form validation errors on the client side.
Remember, the best way to learn programming is by doing. So, try to solve these exercises without looking at the solutions first!
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Sign Up')
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
if form.password.data == 'hardcoded_password':
return 'Logged in!'
else:
return 'Invalid password.'
return render_template('login.html', form=form)
form.errors
in your template:{% for field, errors in form.errors.items() %}
{% for error in errors %}
<div class="alert alert-danger">
{{ error }}
</div>
{% endfor %}
{% endfor %}
Keep practicing and happy coding!