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.
Section overview
5 resourcesCovers 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
-
Create a login form with email and password fields.
-
Extend the login form by adding validation to check if the email is in the format
name@example.comand the password is at least 8 characters long. -
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
-
The solution involves creating a
LoginFormclass withEmailFieldandPasswordFieldattributes. -
For the email validation, you can use
wtforms.validators.Email. For the password, you can create a custom validator function. -
Similar to the login form, but with an additional
PasswordFieldfor 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article