Handling Forms and Requests in Flask

Handling forms is a critical part of most web applications — whether it’s a login form, a contact form, or a comment box. In this post, we’ll break down how to properly handle HTML forms in Flask, including:

  • Displaying a form with HTML
  • Handling POST and GET requests
  • Validating form input
  • Providing user feedback

Basic Flask Setup

# app.py
from flask import Flask, render_template, request, redirect, url_for, flash

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

Step 1: Create an HTML Form

templates/form.html

<!DOCTYPE html>
<html>
<head>
  <title>Simple Form</title>
</head>
<body>
  <h2>Contact Us</h2>

  <form method="POST" action="/submit">
    <label>Name:</label><br>
    <input type="text" name="name" required><br><br>

    <label>Message:</label><br>
    <textarea name="message" required></textarea><br><br>

    <button type="submit">Send</button>
  </form>

  {% with messages = get_flashed_messages() %}
    {% if messages %}
      <ul>
        {% for msg in messages %}
          <li>{{ msg }}</li>
        {% endfor %}
      </ul>
    {% endif %}
  {% endwith %}
</body>
</html>

Step 2: Handle Form Submission in Flask

@app.route('/')
def home():
    return render_template('form.html')

@app.route('/submit', methods=['POST'])
def submit():
    name = request.form.get('name')
    message = request.form.get('message')

    if not name or not message:
        flash('All fields are required!')
        return redirect(url_for('home'))

    # Here you would typically save to a database
    flash(f"Thanks, {name}! Your message was received.")
    return redirect(url_for('home'))

What’s Happening Here?

  • request.form.get('name'): Safely gets the submitted form data
  • flash(): Stores a temporary message shown after redirect
  • redirect() + url_for(): Prevents form resubmission on refresh (Post/Redirect/Get pattern)

Step 3: Test It Out

Run your app:

flask run

Open http://localhost:5000, fill out the form, and submit. You’ll see a flash message on success!

Bonus: Adding Simple Validation

You can manually validate fields before using them:

if len(name) < 3:
    flash("Name must be at least 3 characters long.")
    return redirect(url_for('home'))

For more advanced forms (e.g. email, password fields, CSRF protection), look into Flask-WTF, which adds built-in form validation and helpers.

Leave a Reply

Your email address will not be published. Required fields are marked *