使用 get_context_data() 返回渲染

时间:2021-05-25 09:43:20

标签: django

场景是我试图呈现一个特定的班级部分和不属于任何部分的学生列表。

如何使用基于函数的视图来实现这一点?

这是我的代码不起作用,但至少是这个想法:

def get_students(request, pk):
    section = Section.objects.get(id=pk)

    def get_context_data(self, **kwargs):

        context = super(get_students(request, pk), self).get_context_data(pk)
        context['section'] = section
        context['students'] = Account.objects.filter(Q(is_student=True) | Q(is_assigned=False)).order_by(
        'last_name', 'first_name')

        return context

    return render(request, 'driver-list-modal.html', get_context_data(pk))

我描绘的模板将包含班级部分名称和未分配学生的表格,其中带有一个复选框,如果选中,则将他们包含在该部分中。

感谢您的回答!

1 个答案:

答案 0 :(得分:3)

在基于类的视图中,视图类有一个方法 get_context_data,它返回一个字典(键值对),我们希望将其用作上下文用于模板。

您尝试在视图中编写一个函数,并通过使用 self 作为参数并调用 super 来使用它,就像您的视图是基于类的视图一样。这当然会给你一个错误,因为 get_students is not a class。您需要做的只是创建一个字典并将其作为上下文传递:

def get_students(request, pk):
    section = Section.objects.get(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)
相关问题