Home > Software engineering >  Flask - Creating dynamic URL based on user input
Flask - Creating dynamic URL based on user input

Time:02-11

I'm trying to create a dynamic URL based on user's input from an HTML form.

For example, if a user types in 'AAPL' or 'KO', the next page should be: webapp.com/result/AAPL or webapp.com/result/KO

index.html:

<div  id="cell-1-2">
  <span  style="text-align: center;">
      <form action="{{ url_for('ticker_result', variable='variable') }}" method="POST">
      <input type="text" name="variable" placeholder="search ticker or company" maxlength="4" 
             font-size="24px" style="text-transform:uppercase">
      <input  type="submit" value="Search" onclick="tickerSymbol();">
    </form>
  </span>
</div>

I've tried renaming the 'variable' part to several different things and nothing works so I'm just stuck at this point.

main.py:

# Routing to the homepage
@app.route("/")
def markert_hours_today():
    return render_template(
        "index.html")

# Routing to the result page
@app.route("/result/<variable>", methods = ["GET", "POST"])
def ticker_result(variable):
    if request.method == "POST":
        result = request.form["variable"]
        return render_template(
            "result.html", 
            result=result)

When I run the local environment, and type in a ticker symbol, the next URL is: webapp.com/result/variable

I'm assuming it's HTML that I need to edit? I've read the quickstart documentation for Flask which isn't making sense to me and looked up similar questions but I can't seem to find an answer to this.

CodePudding user response:

You are coming at it from the wrong way. When Jinja creates index.html based on your template you can't know what variable is going to be, so how is Jinja supposed to know?

What you need to do is send the form back to the same route and then redirect the user to whatever they typed in. So something like this:

from flask import request, redirect, url_for

@app.route("/", methods=['GET', 'POST'])
def markert_hours_today():
    if request.method == 'POST':
        result = request.form['variable']
        return redirect(url_for('ticker_result', variable=result)
    return render_template("index.html")

Edit: forgot to rename variable from user_input to result.

  • Related