Flask / Flask Forms and Validation

Building Secure Forms with Flask-WTF

In this tutorial, you'll learn how to build secure forms using Flask-WTF. We'll cover topics such as form validation, CSRF protection, and secure form handling.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers creating and handling forms with Flask and performing validation.

1. Introduction

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:

  • Understand what Flask-WTF is and how it works
  • Create a secure form using Flask-WTF
  • Validate form data
  • Protect your form against CSRF (Cross-Site Request Forgery) attacks

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.

2. Step-by-Step Guide

What is Flask-WTF?

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.

Creating a Secure Form with Flask-WTF

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.

Form Validation

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)

3. Code Examples

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.

4. Summary

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.

5. Practice Exercises

  1. Exercise: Create a form with more fields (e.g., email, password, etc.) and apply appropriate validators to each field.

  2. Exercise: Implement a login form and check the submitted password against a hardcoded password.

  3. 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!

Solutions

  1. Here's an example of a form with more fields:
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')
  1. Here's how you can check the submitted password against a hardcoded password:
@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)
  1. To render form validation errors, you can check 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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help