-
Notifications
You must be signed in to change notification settings - Fork 4
multistep forms
In the previous section, you saw how to use hidden variables to save application state (basically, variables) across multiple webpage requests and responses. Now, we will use our new knowledge to re-write our random number generator using a multistep form. In other words, we will have one page that asks for the lower limit, then a separate page that asks for the upper limit, then a third page that generates the random number. In the real world, there's no particular reason to break it up this way, but you will see a new technique to manage what "step" of the form you are on.
When creating multistep forms, one way to break up the steps is to have a different route and/or HTML template for each step. Try making three HTML templates:
random1.html
<html>
<head>
<title>Random</title>
</head>
<body>
<h1>Random numbers are fun!</h1>
<form action="{{ url_for('random2') }}" method="post">
Pick a lower limit: <input type="text" name="lowerlim"><br>
<input type="submit" value="Next">
</form>
</body>
</html>random2.html
<html>
<head>
<title>Random</title>
</head>
<body>
<h1>Random numbers are fun!</h1>
<form action="{{ url_for('random3') }}" method="post">
Thanks, you picked {{low}}.<br>
Pick an upper limit: <input type="text" name="upperlim"><br>
<input type="hidden" name="lowerlim" value="{{low}}">
<input type="submit" value="Generate">
</form>
</body>
</html>random3.html
<html>
<head>
<title>Random</title>
</head>
<body>
<h1>Random numbers are fun!</h1>
Your random number is: {{number}}.<br>
</body>
</html>Notice how instead of having a single HTML template handling all of the logic, we now have three templates, one for each step of the process:
-
random1.htmldisplays the form for getting the lower limit. The form usesurl_forto pass the submitted information to therandom2route in Flask. -
random2.htmldisplays the form for getting the upper limit, along with confirmation of the lower limit. Similarly to the previous page, the form passes the information along to therandom3route. -
random3.htmldisplays the final generated number
Now let's look at the Flask app:
from flask import Flask, render_template, request
import random
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route("/random", methods=['get', 'post'])
def random1():
return render_template("random1.html")
@app.route("/random2", methods=['get', 'post'])
def random2():
lower = int(request.form['lowerlim'])
return render_template("random2.html", low=lower)
@app.route("/random3", methods=['get', 'post'])
def random3():
print(request.form)
lower = int(request.form['lowerlim'])
upper = int(request.form['upperlim'])
n = random.randint(lower, upper + 1)
return render_template("random3.html", number=n)- Notice how the Flask routes are synchronized with both their corresponding function names and the HTML templates that generate them. This can be handy to keep everything straight. The one place the names are not synchronized is in the HTML templates themselves (see above) --- you will notice that
random1.htmlpasses the form information torandom2.htmlwhich passes it torandom3.html.
Some people don't like having separate HTML templates for each step of the form. Similarly, some people don't like having separate Flask routes/Python functions for each separate step. Typically, both reasons for disliking it is that usually there is some information that the three templates or routes have in common that ends up being duplicated. For instance, notice that in all three of the HTML templates, the title is the same, as well as the h1 header. (Note that this can also be handled with nested HTML templates, which is a separate topic.) The Python code doesn't share much in common between the three routes, but this often changes when you add in things like opening a database. At any rate, here is a different way of doing things that accomplishes the same result. We will combine all three routes together into one, as well as all three HTML templates into one. These tasks can also be done individually.
Check this out:
<html>
<head>
<title>Random</title>
</head>
<body>
<h1>Random numbers are fun!</h1>
{% if step == "choose_lower" %}
<form action="{{ url_for('do_random') }}" method="post">
Pick a lower limit: <input type="text" name="lowerlim"><br>
<input type=hidden name="step" value="choose_upper">
<input type="submit" value="Next">
</form>
{% elif step == "choose_upper" %}
<form action="{{ url_for('do_random') }}" method="post">
Thanks, you picked {{low}}.<br>
Pick an upper limit: <input type="text" name="upperlim"><br>
<input type="hidden" name="lowerlim" value="{{low}}">
<input type="hidden" name="step" value="show_number">
<input type="submit" value="Generate">
</form>
{% elif step == "show_number" %}
Your random number is: {{number}}.<br>
{% endif %}
</body>
</html>from flask import Flask, render_template, request
import random
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route("/random", methods=['get', 'post'])
def do_random():
# Note that we are not calling this function plain "random()" because random
# is the name of a package we imported.
# Step 1, display lower limit form
if "step" not in request.form:
return render_template("random.html", step="choose_lower")
# Step 2, accept lower limit from form, display upper limit
elif request.form["step"] == "choose_upper":
lower = int(request.form['lowerlim'])
return render_template("random.html", step="choose_upper", low=lower)
# Step 3, accept lower+upper limits from form, display random number
elif request.form["step"] == "show_number":
lower = int(request.form['lowerlim'])
upper = int(request.form['upperlim'])
n = random.randint(lower, upper + 1)
return render_template("random.html", step="show_number", number=n)Use the main wiki page to navigate, not the list of pages directly above, because those are out of order.