How to pass variables between HTML pages using Flask

假装没事ソ 提交于 2020-12-12 21:52:36

问题


I'm new to using Flask and I've just been trying to pass a variable between two web pages. The first is a simple form to accept a number with the second page just displaying what is entered.

HTML for the form page:

<!doctype html>
<html>
<body>
    <form action ="{{ url_for('return_form', glon="glon") }}" method="post">
            Galactic Longitude: <input type="text" name="glon">
        <button type="submit">Submit</button>
    </form>
</body>
</html> 

HTML for the display page:

<!doctype html>
<body>

<p> {{ glon }} </p>

</body>
</html>

The Flask script currently looks like this:

from flask import Flask
from flask import render_template, url_for, request, redirect
app = Flask(__name__)

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

@app.route('/form/', methods = ['GET', 'POST'])
def form():
    if request.method == 'POST':
        glon = request.form['glon']
        #glat = request.form['glat']

        return redirect(url_for('return_form', glon=glon))

    return render_template('form.html')

@app.route('/return_form/<glon>', methods = ['GET', 'POST'])
def return_form(glon):
    return render_template('return_form.html', glon=glon)

if __name__ == '__main__':
    app.run()

At the moment, the second page just displays "glon" instead of the number passed to the form.

I simply want the variable to display on the second page, and eventually use it in the return_form function.


回答1:


So i didn't got your approach.Below is what i did,I changed the code a bit. Hope this solves your problem.

main.py

from flask import Flask
from flask import render_template, url_for, request, redirect
app = Flask(__name__)

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

@app.route('/form', methods = ['GET', 'POST'])
def form():
    if request.method == 'POST':
        glon = request.form['glon']
        return render_template('display.html', glon=glon)

# @app.route('/return_form/<glon>', methods = ['GET', 'POST'])
# def return_form(glon):
#     return render_template('return_form.html', glon=glon)

if __name__ == '__main__':
    app.run()

index.html

<html>
<body>
    <form action ="{{ url_for('form') }}" method="post">
            Galactic Longitude: <input type="text" name="glon">
        <button type="submit">Submit</button>
    </form>
</body>
</html>

display.html

<!doctype html>
<body>

<p> {{ glon }} </p>

</body>
</html>


来源:https://stackoverflow.com/questions/51726922/how-to-pass-variables-between-html-pages-using-flask

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!