2
我對Flask和web開發非常陌生,在從mongdb查詢中生成列表並將其傳遞給在Flask中的下拉菜單中的html模板時遇到了一些麻煩。從燒瓶中的下拉列表中選擇
請參閱下面的當前代碼:
views.py
from flask import render_template
from app import app
from pymongo import MongoClient
@app.route('/')
@app.route('/index')
def index():
user = {'name': 'Bob'}
client = MongoClient()
client = MongoClient('mongodb://localhost:27017/')
db = client.test_database
db = client['test-database']
collection = db.test_collection
posts = db.posts
name_list = []
for post in posts.find({'type': "server"}):
name_list.append(post['name'])
# Get selected option and save into variable?
#if:
# choice = x.option
return render_template("index.html",
title='Database selector',
user = 'Bob',
server_list=name_list)
server_list包含: [u'server1' ,u'server2' ,u'server3' ]
索引.html模板
<html>
<head>
<title>{{ title }} - Test</title>
</head>
<body>
<h1>Hi, {{ user }}!</h1>
<h2>Option selector</h2>
<h3><table><form action="" method="POST">
<td>
<label>Select :</label>
<select name="option" width="300px">
{% for x in server_list %}
<option value="{{ x.option }}" SELECTED>{{ x.option }}</option>
{% endfor %}
</select>
</td>
</form></table></h3>
</body>
</html>
首先,選擇列表沒有被填充其次,是否有人會對如何捕獲選擇結果提供一些建議,以便我可以在另一個數據庫查詢中使用它並生成第二個下拉列表?
任何提示非常感謝。
謝謝
謝謝PJ桑託羅.. - 這一直是非常有幫助的 - 作爲一個延續,我想傳遞的結果的選擇返回到代碼以創建新的數據庫查詢,然後在同一頁面上填充第二個下拉框。我的代碼是這樣的python和jinja ..但是提交的值沒有被正確地返回 - 你有進一步的想法嗎? –
if request.form ['submit'] =='myselect': choice = x sub_name_list = [q ['sub_server'] for posts.find({'type':choice})] return render_template ( 「index.html的」, 標題= '數據庫選擇', 用戶= '鮑勃', server_list = NAME_LIST, sub_server_list = sub_name_list) –
<選擇name = 「選項」 ID =」 sub_myselect「onchange =」this.form.submit()「> {%for sub_server_list%} {%endfor%} –