从烧瓶中的下拉列表中选择

时间:2017-02-26 14:36:49

标签: python mongodb web flask

我对Flask和Web开发都很陌生,并且在从mongdb查询生成列表并将其传递到html模板以便在Flask的下拉菜单中时遇到一些麻烦。

请参阅下面的当前代码:

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']

index.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>

首先,选择列表没有填充,其次,是否有人对如何捕获选择结果有一些建议,以便我可以在另一个数据库查询中使用它并生成第二个下拉列表?

任何提示都非常赞赏。

谢谢

1 个答案:

答案 0 :(得分:2)

你犯了一个非常简单的错误。我也会在这里给你一些额外的清理建议。最终,您在Jinja语法中对x.option的引用不正确。由于它是一个简单的列表,您应该使用x(它没有option属性)。不要忘记使用endfor和endif子句。

<强>的Python:

@app.route('/')
@app.route('/index')
def index():
    user = {'name': 'Bob'}

    client = MongoClient('mongodb://localhost:27017/')
    db = client['test-database']

    collection = db.test_collection
    posts = db.posts
    name_list = [p['name'] for p in posts.find({'type': "server"})]

    return render_template("index.html",
                           title='Database selector',
                           user='Bob',
                           server_list=name_list)

<强>金贾/ HTML:

{% for x in server_list %}
<option value="{{ x }}"{% if loop.first %} SELECTED{% endif %}>{{ x }}</option>
{% endfor %}
相关问题