HTML forms in flask

Take a quick look at HTML forms recap to refresh your memory on HTML forms

Render a form in HTML response

from flask import Flask, request
app = Flask(__name__)

@app.route('/')
def index():
    # Or just put this HTML in a template
    return """
<form method="GET" action="/greeting">
    <input type="text" name="username">
    <input type="submit">
</form>
"""

Feel free to play around with the above snippet by building a form using other inputs like:

  • Select

  • Radio buttons

  • Text area

  • etc.

Handling form response

Notice the action and action attributes on the form element. We will now build a route that can handle the data submitted on the form.

@app.route('/greeting')
def greeting():
    username = request.args.get('username')
    return f"<h1>Hi {username}</h1>"

Last updated