You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Flask新手求助:如何通过PyMongo从MongoDB取数并展示学生列表

Fixing Your Flask Student List Display

Hey there! Let's get your student list working properly—since you're new to Flask and Python, I'll break this down step by step so it makes total sense.

First, Fix the Route Function

Looking at your current code, there are a couple of small but critical issues keeping the student list from showing up correctly:

  1. Skip the dumps() call: MongoDB returns student documents as Python dictionaries, which Flask's Jinja2 templates can work with directly. Converting them to JSON strings with dumps() will just make it impossible to access individual fields like first_name in the template.
  2. Pass a list of students (not a single entry): The find() method returns a cursor (a pointer to the database results), not a ready-to-use list. Convert it to a list so you can iterate over it in the template. Also, your return statement had a typo (stu... instead of the correct variable name).

Here's the corrected route function:

@app.route("/view-students")
def view_students():
    if 'username' not in session:
        return render_template('index.html')
    # Convert the database cursor to a list of student dictionaries
    students = list(mongo.db.students.find())
    # Optional debug print to check what data you're getting
    for student in students:
        print(student)
    # Pass the full list to the template
    return render_template('view-students.html', students=students)

Next, Build the view-students.html Template

Now you need to update your template to display the student list using Jinja2's template syntax. Here's a clean, functional example:

<!DOCTYPE html>
<html>
<head>
    <title>Student List</title>
    <style>
        table { border-collapse: collapse; margin: 20px 0; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <h1>Registered Students</h1>
    
    {% if students %}
        <table>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Student ID</th>
                <th>Major</th>
            </tr>
            {% for student in students %}
            <tr>
                <td>{{ student.first_name }}</td>
                <td>{{ student.last_name }}</td>
                <td>{{ student.student_id }}</td>
                <td>{{ student.major }}</td>
            </tr>
            {% endfor %}
        </table>
    {% else %}
        <p>No students found in the database yet.</p>
    {% endif %}
</body>
</html>

Quick Explanations

  • Cursor to list: list(mongo.db.students.find()) turns the database cursor into a Python list of dictionaries, which Jinja2 can loop through seamlessly.
  • Jinja2 syntax: The {% for student in students %} block iterates over each entry, and {{ student.field_name }} pulls out the value of each student's field. The {% if students %} check handles empty database cases gracefully.
  • Session validation: Your original code's login check is spot-on—this ensures only authenticated users can view the student list.

That's all! Run your Flask app, log in, and head to /view-students—you should see your student list displayed in a clean table.

内容的提问来源于stack exchange,提问作者acd37

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:47:40