django访问模板中的上下文

Rog*_*Liu 4 django templates django-queryset django-context

我的代码是这样的:我自定义我的上下文,并希望在模板中访问我的查询集

class GetStudentQueryHandler(ListView):
    template_name = 'client.html'
    paginate_by = STUDENT_PER_PAGE
    context_object_name = 'studentinfo'

    def get_context_data(self, **kwargs):
        context = super(GetStudentQueryHandler, self).get_context_data(**kwargs)
        context['can_show_distribute'] = self.request.user.has_perm('can_show_distribute_page')
        context['form'] = QueryStudentForm

        return context

    def get_queryset(self):
Run Code Online (Sandbox Code Playgroud)

问题是:如何访问模板中get_queryset方法返回的查询集?我知道我可以访问自定义属性,如studentinfo.can_show_distribute,如何访问查询数据?

sta*_*alk 6

正如它在这里所写,默认的上下文变量ListViewobjects_list

所以在模板中可以访问如下:

{% for obj in objects_list%}
   {{obj.some_field}}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

此外,它可以使用context_object_name参数手动设置(如您的示例中所示):

class GetStudentQueryHandler(ListView):
    # ...
    context_object_name = 'studentinfo'
    # ...
Run Code Online (Sandbox Code Playgroud)

并在模板中:

{% for obj in studentinfo %}
   {{obj.some_field}}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

  • 好吧,你已经做到了:`context = super(GetStudentQueryHandler,self).get_context_data(** kwargs)`。因此,您的上下文将包括ListView添加的所有字段。要从模板访问`can_show_distribute`,请执行以下操作:{{can_show_distribute}},而不要执行以下操作:{{studentinfo.can_show_distribute}} (2认同)
  • @tilaprimera 默认情况下,“ListView”的 *所有* 实例都有名为 [`object_list`] 的变量(https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-display/#making -友好模板上下文)。但是,您可以在“context_object_name”视图类属性中设置特定于当前视图变量名称 (2认同)