Home > Software engineering >  How do I print a user's input in a form onto the website screen
How do I print a user's input in a form onto the website screen

Time:11-13

I'm building a website in flask and python and I want to store the user's input in a variable, then output it onto the website screen.

This is my HTML code:

<!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">
    <title>Home</title>
</head>
<body>
    <div><h1>Home Page</h1>
    <p>Hello, {{ name }}</p>
    </div>

    <form>
        <label for="fname">Enter Sq. ft.</label><br>
        <input type="text" id="estimate" name="estimate" value="Ex. 1000"><br>
        <input type="submit" value="Calculate Estimate">
    </form>

    <a href="/my-link/">Click me</a>
</body>
</html>

and this is my python/flask code:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/my-link/')
def my_link():
    temp = 0
    for i in range(10):
        temp = i

    return str(temp)

if __name__ == '__main__':
    app.run(debug=True, port=8000)

When I run this, this is what I see: home page screen

When I type in 54 and hit "Calculate Estimate", I don't understand why I get http://127.0.0.1:8000/?estimate=54 in my search bar, I don't understand why it's going there. How would I be able to get that 54 and just print it on the website screen?

CodePudding user response:

While I would recommend using POST if you're submitting sensitive data, GET suffices in your case.

To solve your issue, we have to first specify an action endpoint (by default, it's /, which loads too much responsibility onto one endpoint).

  <form action="/calculate-estimate">
      <label for="fname">Enter Sq. ft.</label><br>
      <input type="text" id="estimate" name="estimate" value="Ex. 1000"><br>
      <input type="submit" value="Calculate Estimate">
  </form>

Second, we need to create a FLASK endpoint to handle the form data.

@app.route("/calculate-estimate", methods=["GET"])
def calculate_estimate():
    estimate = request.args.get("estimate")
    ## Use your data however you desire.

This should be enough to solve your issue.

  • Related