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,如何访问查询数据?
正如它在这里所写,默认的上下文变量ListView是objects_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)