【发布时间】:2017-02-28 11:59:02
【问题描述】:
我有一个两管齐下的问题,希望得到任何建议。
1) 我有一个烧瓶模板,里面有多种形式。每个表单都向用户展示了一个从 mongodb 查询动态生成的列表。
name_list = [p['name'] for p in posts.find({'type': "server"})]
name_list.insert(0, "select")
然后在我的 html 模板中引用它(再次感谢在上一个问题上帮助我解决此循环的人)
<select name="option" id="myselect" onchange="this.form.submit()">
{% for x in server_list %}
<option value="{{ x }}"{% if loop.first %} SELECTED{% endif %}>{{ x }}</option>
{% endfor %}
然后将此选择传递回 python 以在另一个数据库查询中使用,然后向用户显示另一个下拉选择框。但是,当提交第一个表单时,新的页面呈现意味着该值现在在 html 上丢失并显示为空白。有没有办法让这个选择保持不变,所以在新页面渲染后它仍然出现?
2) 其次,我想保留用户所做选项的运行列表,但是考虑到 if、elif 结构,我正在使用该变量失去状态并且不能再使用。最终,我想向用户展示两组这样的下拉菜单,以生成最终的数据库查询,我可以比较并返回差异,但是只有在我可以保持循环中生成的这些值的状态时,我才能这样做。
请看下面的完整代码:
蟒蛇:
from flask import render_template
from flask import request
from flask import Response
from app import app
from pymongo import MongoClient
@app.route('/', methods=['POST','GET'])
@app.route('/index', methods=['POST','GET'])
def index():
user = {'name': 'Bob'}
client = MongoClient('mongodb://localhost:27017/')
db = client['test-database']
collection = db.test_collection
name_list = []
posts = db.posts
name_list = [p['name'] for p in posts.find({'type': "server"})]
name_list.insert(0, "select")
select_list = []
#if request.form['submit'] == 'myselect':
if request.method == 'POST' and request.form.get('option'):
choice = request.form.get('option')
select_list.append(choice)
sub_name_list = [q['type'] for q in posts.find({'name': choice})]
return render_template("index.html",
sub_server_list=sub_name_list)
elif request.method == 'POST' and request.form.get('option1'):
choice1 = request.form.get('option1')
select_list.append(choice1)
return render_template("index.html",
title='Database selector',
user='Person',
choiced=choice1,
total_choice=select_list)
return render_template("index.html",
title='Database selector',
user='Person',
server_list=name_list)
html/神社:
<html>
<head>
<title>{{ title }} - Test</title>
</head>
<body>
<h1>Hi, {{ user }}!</h1>
<h2>Database selector</h2>
<h3><table><form action="" method="post">
<td>
<label>Select1 :</label>
<!--<select name="option" width="300px">-->
<select name="option" id="myselect" onchange="this.form.submit()">
{% for x in server_list %}
<option value="{{ x }}"{% if loop.first %} SELECTED{% endif %}>{{ x }}</option>
{% endfor %}
</select>
</td>
</form></table></h3>
<h3><table><form action="" method="post">
<td>
<label>Select2 :</label>
<select name="option1" id="sub_myselect" onchange="this.form.submit()">
{% for y in sub_server_list %}
<option value="{{ y }}"{% if loop.first %} SELECTED{% endif %}>{{ y }}</option>
{% endfor %}
</td>
</form></table></h3>
<h3>Here is the choice: {{ choiced }}</h3>
<h3>Here is the choice: {{ total_choice }}</h3>
</body>
</html>
任何指针或想法将不胜感激。
【问题讨论】:
标签: javascript python web flask