我是Python和Flask的新手。这本质上是一个学生数据库。每个文档都包含first_name
,last_name
,student_id
和major
。我希望在访问/view-students
时显示列表。代码:
@app.route("/view-students")
def view_students():
if 'username' not in session:
return render_template('index.html')
students = mongo.db.students
for student in students.find():
student = dumps(student)
print(student)
return render_template('view-students.html', student=student)
这会以字符串形式返回,或者从google搜索中显示,BSON:
{"last_name": "Down", "student_id": "u6003698", "first_name": "Alec", "_id": {"$oid": "5ae0f4ca78ba1481a6284e83"}, "major": "German Literature"}
{"last_name": "Doe", "student_id": "u0000000", "first_name": "John", "_id": {"$oid": "5ae0f4f178ba1481a6284e84"}, "major": "Electrical Engineering"}
在客户端,我基本上想做这样的事情:
<table class="table">
<thead>
<tr>
<th scope="col">Student ID</th>
<th scope="col">Name</th>
<th scope="col">Major</th>
</thead>
<tbody>
{% for student in students %}
<tr>
{{students.first_name}}
</tr>
{% endfor %}
</tbody>
</table>
我尝试过使用jsonify,json转储,json-utils,所有这些似乎只是给我一个字符串或者告诉我它不能被序列化。
任何帮助都将不胜感激。
答案 0 :(得分:0)
你必须传递一个列表作为参数,不需要转储内容:
@app.route("/view-students")
def view_students():
if 'username' not in session:
return render_template('index.html')
students = list(mongo.db.students.find())
return render_template('view-students.html', students=students)
使用student
而非students
重复模板(请注意 s ):
<table class="table">
<thead>
<tr>
<th scope="col">Student ID</th>
<th scope="col">Name</th>
<th scope="col">Major</th>
</thead>
<tbody>
{% for student in students %}
<tr>
{{student.first_name}}
</tr>
{% endfor %}
</tbody>
</table>