2013-05-09 82 views
2

我的代码是这样的: 我定制我的背景和要访问我的查询在模板中设置Django的访问上下文

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这样的自定义属性,如何访问查询数据?

回答

6

正如书面here,用于ListView默认上下文变量是objects_list

所以在模板它可以如以下进行访问:

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

此外,它可以被手动地与context_object_name参数集(如在你的例子中):

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

and in template:

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

我知道,但我customed我的上下文中get_context_data方法,我添加了“can_show_distribute”,恐怕领域如果我用for循环,我也将访问自定义字段,但我只想显示get_queryset方法返回的数据。 – 2013-05-09 09:16:00

+1

嗯,你已经这样做了:'context = super(GetStudentQueryHandler,self).get_context_data(** kwargs)'。所以你的上下文将包括所有'ListView'添加的字段。要从模板访问'can_show_distribute',你应该这样做:'{{can_show_distribute}}',而不是这个:'{{studentinfo.can_show_distribute}}' – stalk 2013-05-09 09:21:02

+1

所以你的意思是“studentinfo”对象只代表get_queryset返回的查询集方法?好的,我会试一试,如果有效的话,我会接受你的回答,谢谢 – 2013-05-09 09:23:24