0
0
FlaskHow-ToBeginner · 3 min read

How to Get Form Data in Flask: Simple Guide with Examples

In Flask, you get form data by importing request from flask and accessing request.form. This dictionary-like object holds the submitted form fields, which you can retrieve by their names using request.form['field_name'] or request.form.get('field_name').
📐

Syntax

To get form data in Flask, you use the request.form object inside a route that handles POST requests. It works like a dictionary where keys are the names of form fields.

  • request.form['field_name']: Accesses the value of the form field named field_name. Raises an error if the field is missing.
  • request.form.get('field_name'): Safely gets the value or returns None if the field is missing.
python
from flask import Flask, request

app = Flask(__name__)

@app.route('/submit', methods=['POST'])
def submit():
    value = request.form['field_name']  # or request.form.get('field_name')
    return f"Received: {value}"
💻

Example

This example shows a simple Flask app with a form that sends data via POST. The server reads the form data and displays it back.

python
from flask import Flask, request, render_template_string

app = Flask(__name__)

form_html = '''
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Form Example</title></head>
<body>
  <form method="POST" action="/submit">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required>
    <button type="submit">Send</button>
  </form>
</body>
</html>
'''

@app.route('/')
def index():
    return render_template_string(form_html)

@app.route('/submit', methods=['POST'])
def submit():
    username = request.form.get('username')
    return f"Hello, {username}! Your form data was received."
Output
When you open the root URL, you see a form with a username field. After submitting, the page shows: "Hello, [username]! Your form data was received."
⚠️

Common Pitfalls

Common mistakes when getting form data in Flask include:

  • Not specifying methods=['POST'] in the route, so form data is not processed.
  • Using request.args instead of request.form for POST form data.
  • Accessing form fields directly with request.form['field_name'] without checking if the field exists, which raises a KeyError.

Always use request.form.get('field_name') to avoid errors if the field is missing.

python
from flask import Flask, request

app = Flask(__name__)

@app.route('/submit', methods=['POST'])
def submit():
    # Wrong: Using request.args for POST form data
    # username = request.args.get('username')  # This will be None

    # Wrong: Accessing without checking
    # username = request.form['username']  # Raises KeyError if missing

    # Right way:
    username = request.form.get('username')
    if not username:
        return "Username is missing", 400
    return f"Received username: {username}"
📊

Quick Reference

Summary tips for getting form data in Flask:

  • Import request from flask.
  • Use request.form to access POST form data.
  • Use request.form.get('field_name') to avoid errors if the field is missing.
  • Make sure your route allows POST method.
  • Use HTML form with method="POST" and matching name attributes.

Key Takeaways

Use request.form to access form data sent via POST in Flask.
Always specify methods=['POST'] in your route to handle form submissions.
Use request.form.get('field_name') to safely get form values without errors.
Do not confuse request.args (for URL query parameters) with request.form (for POST data).
Ensure your HTML form uses method="POST" and proper name attributes for inputs.