如何将值从下拉列表传递到烧瓶中的另一页

时间:2019-12-15 04:24:16

标签: python flask

我想拥有一个页面,在该页面中,可以从传递到下一页的下拉列表中选择一个选项。我收到的错误是“ UnboundLocalError:分配前引用的本地变量'currentuser'”。我不确定从下拉列表中选择选项后如何全局更新变量,或者如何在下一页函数中本地访问全局变量。我是python和flask的新手,任何帮助将不胜感激!

app.py

from flask import Flask, render_template
import sqlite3
app = Flask(__name__) 

@app.route('/selectusername')
def selectusername_page():
    # connect to database and populate userlist
    conn = sqlite3.connect('users.db')
    c = conn.cursor()
    c.execute("SELECT * FROM users")
    userlist = c.fetchall()
    conn.close()
    return render_template('selectusername.html', userlist=userlist)

@app.route('/showusername')
def showusername_page():
    currentuser=currentuser
    return render_template('showusername.html', currentuser=currentuser)

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

selectusername.html

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<body>
    <button onclick="window.location.href = 'showusername';">Continue</button>
        <h1>Select User</h1>
<select id="currentuser">
{% for user in userlist %}
  <option value="{{user[0]}}">{{user[0]}}</option>
{% endfor %}
</select>
</body>
</html>

showusername.html

<h1>Hello {{ currentuser }}</h1>

1 个答案:

答案 0 :(得分:2)

如果您使用

<form action="/showusername"> 

和没有JavaScript的按钮,而您在name="currentuser"中使用<select>

<select name="currentuser">

然后它可以在url中发送选定的值

/showusername?currentuser=selected_name

您可以使用showusernamerequest.args中获得它

currentuser = request.args.get("currentuser")

要从url中隐藏名称,您将必须使用POST方法-因此必须进行设置

<form action="/showusername" method="POST"> 

在烧瓶中

@app.route('/showusername', methods=['POST', 'GET'])

,然后使用request.form代替request.args

currentuser = request.form.get("currentuser")

完整示例

from flask import Flask, render_template, render_template_string, request

app = Flask(__name__) 

@app.route('/selectusername')
def selectusername_page():

    userlist = [['James'], ['Adam'], ['Mark']]

    return render_template_string('''<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<body>
<form action="/showusername">
    <button>Continue</button>
        <h1>Select User</h1>
<select id="currentuser" name="currentuser">
{% for user in userlist %}
  <option value="{{user[0]}}">{{user[0]}}</option>
{% endfor %}
</select>
</form>
</body>
</html>''', userlist=userlist)

@app.route('/showusername', methods=['POST', 'GET'])
def showusername_page():
    print('args:', request.args)
    print('form:', request.form)

    #currentuser = request.args.get("currentuser")
    currentuser = request.form.get("currentuser")

    return render_template_string('''<h1>Hello {{ currentuser }}</h1>''', currentuser=currentuser)

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

如果要在按钮中使用JavaScript,则必须使用JavaScript来获取选定的值并将其添加到url中,例如

 window.location.href = 'showusername?currentuser=selected_name'

所以它更复杂,我不将代码放在JavaScript中。也许其他人会显示这个。