Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
模板中的django访问上下文_Django_Templates_Django Queryset_Django Context - Fatal编程技术网

模板中的django访问上下文

模板中的django访问上下文,django,templates,django-queryset,django-context,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(GetS

我的代码如下: 我自定义我的上下文并希望访问模板中的查询集

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方法返回的queryset? 我知道我可以访问自定义属性,如studentinfo.can\u show\u distribute,如何访问查询数据?

如文所述,
ListView
的默认上下文变量是
objects\u list

因此,在模板中,可以通过以下方式访问:

{% for obj in objects_list%}
   {{obj.some_field}}
{% endfor %}
此外,还可以使用
context\u object\u name
参数手动设置它(如您的示例所示):

在模板中:

{% for obj in studentinfo %}
   {{obj.some_field}}
{% endfor %}
{{ can_show_distribute }}
要从模板中的上下文访问额外添加的字段
可以\u显示\u分发

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

我知道,但是我已经在get_context_data方法中自定义了我的上下文,我添加了“can_show_distribute”之类的字段,我担心如果我使用for循环,我也会访问自定义字段,但我只想显示get_queryset方法返回的数据。好吧,您已经这样做了:
context=super(GetStudentQueryHandler,self).获取上下文数据(**kwargs)
。因此,您的上下文将包括
ListView
添加的所有字段。要从模板访问
can\u show\u distribute
,您应该这样做:
{can\u show\u distribute}
,而不是这个:
{{studentinfo.can\u show\u distribute}
,那么您的意思是“studentinfo”对象只是表示get\u queryset方法返回的queryset?好的,我会尝试一下,如果成功的话,我会接受你的回答,谢谢you@stalk您的意思是,对于不同的视图,默认的上下文变量可能不同吗?@tilaprimera默认情况下,
ListView
的所有实例都有名为的变量。但是,您可以在
context\u object\u name
view class属性中设置特定于当前视图变量名称