Handling Form Data
HTML forms usually submit data using POST with a content type like:
application/x-www-form-urlencodedmultipart/form-data(required for file uploads)
flowchart TD
A["GET /contact"] --> B["render the empty form"]
B --> C["POST /contact with the data"]
C --> D{"valid?"}
D -->|no| E["re-render the form with errors"]
E --> C
D -->|yes| F["do the work: save, send, charge"]
F --> G["flash a message"]
G --> H["redirect (302) to a GET route"]
H --> I["GET /thanks"]
I --> J["reload is now harmless -- it repeats the GET, not the POST"]
Minimal example (no Flask-WTF yet)
Section titled “Minimal example (no Flask-WTF yet)”Template templates/contact.html:
<form method="post">
<input type="text" name="name" placeholder="Your name" />
<input type="email" name="email" placeholder="Email" />
<button type="submit">Send</button>
</form>Route:
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route("/contact", methods=["GET", "POST"])
def contact():
if request.method == "POST":
name = request.form.get("name", "")
email = request.form.get("email", "")
# TODO: validate input here
return f"Thanks {name}, we received {email}!"
return render_template("contact.html")Common pitfalls
Section titled “Common pitfalls”- Missing
methods=["GET", "POST"]→ POST returns 405 - Forgetting to validate user input
- Returning a success page directly after POST (refresh resubmits)
Best practice: PRG pattern
Section titled “Best practice: PRG pattern”After a successful POST:
- save/process data
redirect()to a GET route
This prevents double submission on refresh.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Create a Flask App
Section titled “Exercise 1 – Create a Flask App”Exercise 2 – Dynamic Route
Section titled “Exercise 2 – Dynamic Route”Exercise 3 – Return JSON
Section titled “Exercise 3 – Return JSON”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading