-1

Trying to get two variables via a html form that will be used in other functions later in the code. For now i just want to print the two variables as a test

index.html is:

<html>
<form action="{{ url_for("user_input")}}" method="post">
    <label for="a_site">A Site:</label>
    <input type="text" id="a_site" name="a_site" placeholder="a_site">
    <label for="z_site">Z Site:</label>
    <input type="text" id="z_site" name="z_site" placeholder="z_site">

    <button> <a href="{{ url_for("results")}}">Submit </a></button>
</form>

</html>

results.html is:

<html>
<body>
    {{ a_site_name }} <br>
    {{ z_site_name }}
</body>
</html>

Python code

from flask import Flask,render_template,request

app = Flask(__name__)

@app.route('/', methods =['GET', 'POST'])
def user_input():
    a_site_name = request.form.get('a_site')
    z_site_name = request.form.get('z_site')
    return render_template('index.html')

@app.route('/results')
def results():
    return render_template('results.html',
        a_site_name=a_site_name,
        z_site_name=z_site_name
        )

def main():
    app.run(host='localhost', port=8080)

if __name__ == "__main__":
    main()

When i click "Submit" in the browser i get a 500 error, in the flask console the error is NameError: name 'a_site_name' is not defined which makes sense since the results function doesn't know what those two vars are...

I'd usually do something like a_site_name, z_site_name = user_input() under my main function but that doesn't seem to work either...

So how can i get this to work? Those two vars will end up being used to do a bunch of other python functions which will be invisible to the user, with the end results being displayed on the browser

1 Answers1

0

I think you mismatched form action attribute and href in submit button. Your form is POST-ed to the action URL but then you go to results URL and there is no form posted there.

Michał Darowny
  • 359
  • 1
  • 10
  • The endpoints do not know what other endpoints have. So to display results you should return correct render on POST in the user_input or something similar. Depends on what you want to achieve. – Michał Darowny May 03 '21 at 17:44