In this video we will assume this Flask app:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
name = request.form.get("name")
email = request.form.get("email")
age = request.form.get("age")
return f"Submitted: Name: {name}, Email: {email}, Age: {age}"
return render_template("03-index.html")
if __name__ == "__main__":
app.run(debug=True)
This app assumes that there is a folder called templates
with an 03-index.html
file that looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTMX Form Example</title>
<script src="https://unpkg.com/htmx.org"></script>
</head>
<body>
<h1>HTMX Form Example</h1>
<form hx-post="/" hx-target="#result">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age"><br><br>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
</body>
</html>
Note how in this case all the hx-
attributes are attached to a form. This is a common pattern when you're dealing with many inputs. When you submit the backend will receive a POST request with all the inputs and will also carry the names that are specified in each individual input. This makes it easy to parse the form data on the backend.