Flask Tutorial Part 5: Handling Forms and User Input
📝 Creating a Simple HTML Form
You can include an HTML form in your template to collect user input:
<form method="POST">
<label>Name: </label><input type="text" name="username"><br>
<input type="submit" value="Submit">
</form>
📥 Handling POST Requests in Flask
Flask allows you to handle GET and POST requests using the methods
parameter in @app.route()
.
from flask import Flask, request
app = Flask(__name__)
@app.route("/submit", methods=["GET", "POST"])
def submit():
if request.method == "POST":
username = request.form["username"]
return f"Hello, {username}!"
return '''
<form method="POST">
<label>Name: </label><input type="text" name="username"><br>
<input type="submit" value="Submit">
</form>
'''
🧠 Understanding request.form
request.form
is a dictionary-like object that contains form data submitted with the POST method.
📌 Summary
- Use HTML
<form>
to collect user input. - Use
methods=["GET", "POST"]
to handle both types of requests. - Use
request.form["fieldname"]
to get form values.
Comments
Post a Comment