Skip to content
Advertisement

How to display flask data on URL path

hi I created a simple website to calculate the square of the number. below is the code

calculate.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="homepage.css">
    <title>Flask </title>
</head>
<body>
    <header>
        square
    </header>
    <div class="congrat">
        {{ result }}
    </div>
</body>
</html>

homepage.html

<form method="post" action="/square">
    <div class="calculate">
        <b>Square</b><br/>Num
        <input type="text" name="number"><br/>
        <input type="submit" value="calculate">
    </div>
</form>

python

@app.route("/square", methods=['POST'])
def square():
    number = request.form["number"]
    return render_template("calculate.html", result = int(number) ** 2)

now I want to display input number in URL path. e.g. http://127.0.0.1:3000/square/10
so I’ve tried this

<form method="post" action="/square/<number>">
    <div class="calculate">
        <b>Square</b><br/>Num
        <input type="text" name="number"><br/>
        <input type="submit" value="calculate">
    </div>
</form>

@app.route("/square/<number>", methods=['POST'])
def square(number):
    number = request.form["number"]
    return render_template("calculate.html", result = int(number) ** 2)

but it didn’t work. What could I do?

Advertisement

Answer

You could get variables directly parsed from Flask URL

@app.route("/square/<number>", methods=['POST'])
def square(number):
    return render_template("calculate.html", result = int(number) ** 2)

Edit:

<form id="your_form" method="post" onsubmit="yourFunction()">
    <input type="text" name="keywords">
    <input type="text" name="number"><br/>
    <input type="submit" value="calculate">
</form>
 <script>
function yourFunction(){
    var action_src = "/square/" + document.getElementsByName("number")[0].value;
    var your_form = document.getElementById('your_form');
    your_form.action = action_src ;
}
</script>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement