You need to enable JavaScript to run this app. 如何使用Django函数式视图渲染指定班级分部及未分配分部的学生列表
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Django函数式视图渲染指定班级分部及未分配分部的学生列表

原代码问题排查
  • 混淆了类视图(CBV)和函数视图(FBV)的写法:get_context_data是类视图的内置方法,FBV 无需嵌套该方法,直接构造上下文字典即可
  • 筛选逻辑错误:使用了|(或)筛选条件,实际需要同时满足「是学生」和「未分配到任何分部」两个条件,应改为&(且)
  • super调用不符合规范:该调用仅在类视图继承父类时使用,FBV 无该用法
  • 未做异常捕获:直接使用Section.objects.get(id=pk)如果找不到对应分部会直接抛出500错误,建议改用get_object_or_404
正确FBV实现

视图代码

from django.shortcuts import get_object_or_404, render, redirect
from django.db.models import Q
from .models import Section, Account # 按需修改为你自己的导入路径

def get_students(request, pk):
    # 获取指定分部,不存在则返回404
    section = get_object_or_404(Section, id=pk)
    # 直接构造上下文
    context = {
        "section": section,
        # 筛选条件:同时满足是学生、未分配到任何分部
        "students": Account.objects.filter(Q(is_student=True) & Q(is_assigned=False)).order_by("last_name", "first_name")
    }
    return render(request, 'driver-list-modal.html', context)

# 学生分配到分部的提交处理视图
def assign_students(request, pk):
    if request.method == "POST":
        section = get_object_or_404(Section, id=pk)
        # 获取表单提交的选中学生ID列表
        selected_ids = request.POST.getlist("student_ids")
        # 批量更新学生分配状态(假设Account模型有section外键字段关联分部,可根据你实际的字段调整)
        Account.objects.filter(id__in=selected_ids).update(
            is_assigned=True,
            section=section
        )
        # 分配完成后跳转回学生列表页
        return redirect("get_students", pk=pk)

路由配置(urls.py)

from django.urls import path
from . import views

urlpatterns = [
    path("section/<int:pk>/students/", views.get_students, name="get_students"),
    path("section/<int:pk>/assign/", views.assign_students, name="assign_students"),
]

模板参考示例(driver-list-modal.html)

<h2>当前分部:{{ section.name }}</h2>
<form action="{% url 'assign_students' section.pk %}" method="post">
    {% csrf_token %}
    <table border="1">
        <tr>
            <th>选择</th>
            <th>姓氏</th>
            <th>名字</th>
        </tr>
        {% for student in students %}
        <tr>
            <td><input type="checkbox" name="student_ids" value="{{ student.id }}"></td>
            <td>{{ student.last_name }}</td>
            <td>{{ student.first_name }}</td>
        </tr>
        {% empty %}
        <tr>
            <td colspan="3">暂无未分配的学生</td>
        </tr>
        {% endfor %}
    </table>
    <button type="submit">将选中学生加入当前分部</button>
</form>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 21:45:05