Flask / Flask Forms and Validation

Handling Form Submissions with Flask

In this tutorial, we'll explore how to handle form submissions using Flask. You'll learn how to process user input and respond appropriately to form submissions.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers creating and handling forms with Flask and performing validation.

Introduction

In this tutorial, we aim to explore how to handle form submissions using Flask, a micro web framework written in Python. Flask is known for its simplicity and scalability, making it suitable for a variety of web projects.

By the end of this tutorial, you will learn:
- How to create web forms with Flask
- How to validate form input data
- How to respond to form submissions

Prerequisites:
- Basic knowledge of Python
- Familiarity with HTML
- A working installation of Flask

Step-by-Step Guide

Creating Forms in Flask

Flask doesn't have built-in form handling capability. Instead, it works well with WTForms, a flexible form rendering and validation library. Install it using pip:

pip install flask-wtf

To create a form, you define a class that inherits from flask_wtf.FlaskForm. Each class attribute represents a field in the form.

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')

Rendering Forms in Templates

Flask uses Jinja2 templating engine. In your HTML file, use {{ form.field_name.label }} to render a field's label and {{ form.field_name() }} to render the field itself.

<form method="POST">
    {{ form.hidden_tag() }}
    {{ form.name.label }} {{ form.name() }}
    {{ form.submit() }}
</form>

Handling Form Submissions

In your route, validate form data with form.validate_on_submit(). If it's a POST request and the form data is valid, this method returns True.

from flask import Flask, render_template
from forms import MyForm

app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecretkey'

@app.route('/', methods=['GET', 'POST'])
def home():
    form = MyForm()
    if form.validate_on_submit():
        return 'Form Successfully Submitted!'
    return render_template('index.html', form=form)

Code Examples

Let's create a simple contact form that accepts a user's name and email.

forms.py:

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, Email

class ContactForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    submit = SubmitField('Submit')

app.py:

from flask import Flask, render_template
from forms import ContactForm

app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecretkey'

@app.route('/contact', methods=['GET', 'POST'])
def contact():
    form = ContactForm()
    if form.validate_on_submit():
        return 'Thank you for your message!'
    return render_template('contact.html', form=form)

contact.html:

<form method="POST">
    {{ form.hidden_tag() }}
    {{ form.name.label }} {{ form.name() }}<br>
    {{ form.email.label }} {{ form.email() }}<br>
    {{ form.submit() }}
</form>

Summary

In this tutorial, you've learned how to create and validate forms using Flask and WTForms, and handle form submissions in your routes. To continue learning, consider exploring how to use Flask with a database, such as SQLite or PostgreSQL.

Practice Exercises

  1. Create a login form with email and password fields.

  2. Extend the login form by adding validation to check if the email is in the format name@example.com and the password is at least 8 characters long.

  3. Create a form for user registration. Include fields for email, password, and password confirmation. Validate that the email is not already registered and that the password and confirmation match.

Solutions

  1. The solution involves creating a LoginForm class with EmailField and PasswordField attributes.

  2. For the email validation, you can use wtforms.validators.Email. For the password, you can create a custom validator function.

  3. Similar to the login form, but with an additional PasswordField for the confirmation. For the email validation, you'll need to interact with your database to check if the email is already registered.

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

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

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