Skip to main content

Creating forms in Flask

Before we start, it is important to understand what forms are and why they are necessary. Forms are an integral part of any web application. They allow users to submit data to the server. For instance, when you log in to any website, you are actually filling out a form with your username and password, which is then sent to the server.

In Flask, forms are handled using a special extension called Flask-WTF. It provides a set of tools to handle forms, including CSRF (Cross-Site Request Forgery) protection, which is a very common type of web application vulnerability.

In this tutorial, we will guide you on how to create forms in Flask using the Flask-WTF extension. This tutorial is designed to be comprehensive and beginner-friendly. So, let's get started!

Installation

Firstly, we need to install Flask-WTF using pip, which is a package manager for Python.

pip install flask-wtf

Create a Form

To create a form, we need to create a class that inherits from FlaskForm. Each field in the form is represented by a class variable. Flask-WTF includes built-in form fields for different types of data: text fields, number fields, date fields, etc.

Here is a simple form with a text field and a submit button.

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

Render the Form

To render the form in the HTML, we use the form object in the template. Here is an example using the Jinja2 templating engine which comes built-in with Flask.

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

The {{ form.hidden_tag() }} is used for CSRF protection. It generates a hidden field that includes a token that is used to protect the form against CSRF attacks.

Handling Form Submission

When the form is submitted, we can validate it by calling the validate_on_submit() method. If it returns True, it means the form data is valid and we can process it.

from flask import Flask, render_template, request
from forms import MyForm

app = Flask(__name__)

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

Conclusion

With Flask-WTF, it is easy to handle forms in Flask. You can create forms, render them in templates, and handle their submission with just a few lines of code. Remember to always validate your forms before processing them to ensure the data is correct and secure.