Creating and Validating Forms in Flask

Tutorial 1 of 5

1. Introduction

This tutorial aims to demonstrate how to create and validate forms using Flask, a lightweight Python web framework. You will learn how to define a Flask form, handle form submissions, and validate user input.

By the end of this tutorial, you will be able to:

  • Create a basic form in Flask
  • Handle form submissions
  • Validate user input using Flask-WTF

Prerequisites:

  • Basic knowledge of Python
  • Familiarity with HTML forms
  • A basic understanding of Flask

2. Step-by-Step Guide

To create and validate forms in Flask, we will use Flask-WTF, a Flask extension that simplifies form handling in Flask. It provides a simple interface for creating forms and includes built-in CSRF (Cross-Site Request Forgery) protection.

Flask-WTF Installation

You can install Flask-WTF using pip:

pip install flask-wtf

Form Definition

In Flask-WTF, each form is represented as a class, which inherits from the FlaskForm class. Each class variable represents a field in the form.

Here's an example of a simple login form:

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Length

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])
    password = PasswordField('Password', validators=[DataRequired()])
    submit = SubmitField('Login')

In this example, StringField and PasswordField represent text and password input fields, respectively. SubmitField represents a submit button. DataRequired and Length are validators that check if the field is not empty and meets the length requirements.

Form Rendering

To display the form in an HTML template, you can use the form macro provided by Flask-WTF. Here's an example:

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

Remember to include form.hidden_tag() in your form to protect against CSRF attacks.

Form Submission Handling

To handle form submissions in Flask, you can use the request object provided by Flask. Here's an example:

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        # Handle successful form submission
        return 'Form submitted successfully'
    return render_template('login.html', form=form)

In this example, form.validate_on_submit() checks if the form has been submitted and whether the data passes all the validators.

3. Code Examples

Example 1: Creating a Registration Form

Let's create a registration form with username, email, and password fields.

# registration_form.py
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email, EqualTo

class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('Register')

In this example, the Email validator checks if the email field contains a valid email address, and the EqualTo validator checks if the password and confirm_password fields match.

Example 2: Handling Form Submission

Next, we'll create a route in our Flask application to handle the registration form submission.

# app.py
from flask import Flask, render_template, request
from registration_form import RegistrationForm

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        # Handle successful form submission
        return 'Registration successful'
    return render_template('register.html', form=form)

In this example, if the form is valid, the message "Registration successful" will be returned. Otherwise, the registration form will be displayed.

4. Summary

In this tutorial, we've covered how to create and validate forms in Flask using Flask-WTF. We've learned how to define form classes, render forms in templates, and handle form submissions.

Next, you could learn more about Flask-WTF's advanced features, such as form field types, validators, and custom validation methods. You may also want to explore how to integrate Flask forms with a database to store submitted data.

5. Practice Exercises

  1. Create a contact form with fields for name, email, and message.

  2. Add custom validation to the contact form to check that the message is not too long.

  3. Create a login form and validate the user's credentials against a hard-coded list of usernames and passwords.

Remember to use Flask-WTF's built-in validators and form field types where appropriate. Also, remember to handle form submissions and display any validation errors to the user.