🎓 A1Learner
🔍
0 of 50 lessons completed

Flask HTML Forms

An HTML form collects typed values on a page. The form sends the values to a route.

Make the app

This line imports Flask and render_template_string together. The route below shows a form.

from flask import Flask, render_template_string

app = Flask(__name__)

Show the form

The view renders a form with one input named word. The form posts to /echo.

@app.route("/form")
def form():
    return render_template_string('<form action="/echo" method="post"><input name="word"><button>Send</button></form>')

Ask for the form

The test client asks for /form and prints the form HTML.

client = app.test_client()
print(client.get("/form").data.decode())

Example

from flask import Flask, render_template_string

app = Flask(__name__)

@app.route("/form")
def form():
    return render_template_string('<form action="/echo" method="post"><input name="word"><button>Send</button></form>')

client = app.test_client()
print(client.get("/form").data.decode())

Key points

  • A <form> holds inputs and a submit button.
  • Each input needs a name, like name="word".
  • The action names the route that takes the form.
  • The method names the HTTP method, usually POST.

In this example, the view renders a form with one input named word and a Send button. The form posts to /echo. The test client asks for /form and prints the form HTML.

Note

A form without a method sends GET.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the input name do in a form?