【问题标题】:How to get all IdObjects in MongoDB using DropDownMenu in Flask如何在 Flask 中使用 DropDownMenu 获取 MongoDB 中的所有 IdObject
【发布时间】:2019-10-03 09:04:14
【问题描述】:

我的目标是使用 Bootstrap 的 dropdownMenu,其中菜单中的每个项目都获取我的 MongoDB 的 IdObject。

原因是我想将这些 IdObject 放在一个列表中,以便获取存储在该集合中的所有数据。因此,这是我的代码:

HTML

<div class="dropdown-menu" aria-labelledby="dropdownMenu2">
    {% for row in rows %}
       <button class="dropdown-item" href="./get_object?_id={{row['_id']}}" type="button">{{row['_id']}}</button>
    {% endfor %}
</div>

Python

@app.route("/get_object", methods=['POST', 'GET'])
def get_object():
    cursor = object_collection.find({})
    for document in cursor:
        row = document['_id']
        return render_template("get_object.html", rows=row)

不知何故,我没有得到我想要的。我在 python 文件和 HTML 中有一些错误。我的做法好吗?

  File "˜/application/app.py", line 52, in get_object
    return render_template("get_object.html", rows=row)

  File ˜/application/templates/get_object.html", line 18, in block "content"
    {% for row in rows %}

【问题讨论】:

    标签: python html mongodb flask


    【解决方案1】:

    你只想要一个列表。现在你在for 循环中有return。相反,只需附加到列表并立即使用整个列表调用模板:

    @app.route("/get_object", methods=['POST', 'GET'])
    def get_object():
        rows = []                               # define an empty list
        cursor = object_collection.find({},{ "_id": 1 })
        for document in cursor:
            rows.append(document['_id'])        # <- append to the list
    
        return render_template("get_object.html", rows=rows)  # Use the whole list in output
    

    另请注意,投影中的.find({},{ _id: 1 }) 产生_id 字段而不是整个对象。因此,当您只需要 _id 值时,这很有用,这样就不会通过网络发送不必要的数据。

    在您的模板中,现在只是一个列表,因此没有_id 属性。只需使用值:

    <button class="dropdown-item" href="./get_object?_id={{row}}" type="button">{{row}}</button>
    

    【讨论】:

    • 成功了!非常感谢 :) 只是错过了 _id 中的引号,所以应该是 cursor = object_collection.find({},{" _id": 1 })
    • @TimLuka 是的,我错过了报价。最近在 JavaScript 上的时间比在 python 上的时间要多。添加的键上的引号。
    猜你喜欢
    • 2019-10-25
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多