django访问模板中的上下文

时间:2013-05-09 08:57:02

标签: 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):

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

1 个答案:

答案 0 :(得分:6)

在撰写here时,ListView的默认上下文变量为objects_list

因此,在模板中,可以按如下方式访问:

{% for obj in objects_list%}
   {{obj.some_field}}
{% endfor %}

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

class GetStudentQueryHandler(ListView):
    # ...
    context_object_name = 'studentinfo'
    # ...

并在模板中:

{% for obj in studentinfo %}
   {{obj.some_field}}
{% endfor %}

要从模板中的上下文访问附加添加的字段can_show_distribute

{{ can_show_distribute }}