Handling Form Submissions with Flask

Tutorial 2 of 5

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.