首页 > 解决方案 > 如何将下拉列表中的值传递到烧瓶中的另一个页面

问题描述

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

应用程序.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)

选择用户名.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>

显示用户名.html

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

标签: pythonflask

解决方案


如果你使用

<form action="/showusername"> 

和按钮没有JavaScript和你name="currentuser"使用<select>

<select name="currentuser">

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

/showusername?currentuser=selected_name

你可以showusername使用它request.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. 也许其他人会展示这一点。


推荐阅读