Handling Form Data in Flask - 3 Practical Examples

Learn how to effectively handle form data in Flask with these three practical examples.
By Taylor

Examples of Handling Form Data in Flask

Handling form data in Flask is a crucial skill for any web developer. Forms are the primary way users interact with web applications, and understanding how to process this data is key to creating dynamic and responsive applications. Below are three diverse examples that will guide you through different scenarios for handling form data in Flask.

Example 1: Basic Form Submission

This example demonstrates a simple form submission where users enter their name and receive a personalized greeting. It’s perfect for understanding the basics of form handling.

To set up your Flask application, start with the following code:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
    greeting = ''
    if request.method == 'POST':
        name = request.form.get('name')
        greeting = f'Hello, {name}!'
    return render_template('index.html', greeting=greeting)

if __name__ == '__main__':
    app.run(debug=True)

In your index.html file, add the following HTML code:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Greeting Form</title>
</head>
<body>
    <h1>Greeting Form</h1>
    <form method="POST">
        <label for="name">Enter your name:</label>
        <input type="text" id="name" name="name" required>
        <button type="submit">Submit</button>
    </form>
    <p>{{ greeting }}</p>
</body>
</html>

This application will display a form where users can input their names. Once submitted, it will greet them with their name. Remember to run your Flask app and access it in your browser. This basic example sets the foundation for handling more complex forms.

Example 2: Handling Multiple Form Inputs

In this example, you’ll learn how to handle multiple form inputs and display the data back to the user. This is useful for scenarios like user registration where multiple fields are involved.

Here’s how you can set it up:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/register', methods=['GET', 'POST'])
def register():
    user_info = {}
    if request.method == 'POST':
        user_info['username'] = request.form.get('username')
        user_info['email'] = request.form.get('email')
        user_info['password'] = request.form.get('password')
    return render_template('register.html', user_info=user_info)

if __name__ == '__main__':
    app.run(debug=True)

In the register.html file, use the following HTML code:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Registration</title>
</head>
<body>
    <h1>User Registration</h1>
    <form method="POST">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" required>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required>
        <button type="submit">Register</button>
    </form>
    {% if user_info %}
        <h2>Registration Successful!</h2>
        <p>Username: {{ user_info.username }}</p>
        <p>Email: {{ user_info.email }}</p>
    {% endif %}
</body>
</html>

This code allows users to register by providing a username, email, and password. Upon successful submission, the information is displayed back to the user. This is a great way to familiarize yourself with handling multiple form inputs in Flask.

Example 3: Validating Form Data

Form validation is essential for ensuring the integrity of the data submitted. In this example, we’ll create a form that includes validation checks before processing the data.

Here’s how you can implement it:

from flask import Flask, render_template, request, flash, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email, Length

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # Needed for flashing messages

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

@app.route('/validate', methods=['GET', 'POST'])
def validate():
    form = RegistrationForm()
    if form.validate_on_submit():
        # Here, you would typically save the data to a database
        flash('Registration Successful!', 'success')
        return redirect(url_for('validate'))
    return render_template('validate.html', form=form)

if __name__ == '__main__':
    app.run(debug=True)

In your validate.html file, use the following HTML code:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form Validation</title>
</head>
<body>
    <h1>Registration Form</h1>
    {% with messages = get_flashed_messages() %}
        {% if messages %}
            <ul>
            {% for message in messages %}
                <li>{{ message }}</li>
            {% endfor %}
            </ul>
        {% endif %}
    {% endwith %}
    <form method="POST">
        {{ form.hidden_tag() }}
        {{ form.username.label }} {{ form.username(size=32) }}
        {{ form.email.label }} {{ form.email(size=32) }}
        {{ form.password.label }} {{ form.password(size=32) }}
        {{ form.submit() }}
    </form>
</body>
</html>

This example introduces Flask-WTF for form handling and validation. It ensures that all fields are filled correctly before submission. If validation fails, users will be prompted to correct their input. This is crucial for maintaining data quality and improving user experience.

These examples of handling form data in Flask should help you get started with building forms for your web applications. As you practice, remember that the key is to keep learning and experimenting! Happy coding!