【问题标题】:django access context in template模板中的django访问上下文
【发布时间】:2013-05-09 08:57:02
【问题描述】:

我的代码是这样的: 我自定义了我的上下文并想访问我在模板中设置的查询

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

【问题讨论】:

    标签: django templates django-queryset django-context


    【解决方案1】:

    正如 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 }}
    

    【讨论】:

    • 我知道,但是我在get_context_data方法中自定义了我的上下文,我添加了'can_show_distribute'之类的字段,恐怕如果我使用for循环,我也会访问自定义字段,但我只想显示get_queryset方法返回的数据。
    • 好吧,你已经做到了:context = super(GetStudentQueryHandler, self).get_context_data(**kwargs)。因此,您的上下文将包括 ListView 添加的所有字段。要从模板访问can_show_distribute,您应该这样做:{{can_show_distribute}},而不是这样:{{studentinfo.can_show_distribute}}
    • 所以你的意思是“studentinfo”对象只是代表 get_queryset 方法返回的查询集?好的我试试,如果成功我会接受你的回答,谢谢
    • @stalk 你的意思是说对于不同的视图,默认的上下文变量可能不同吗?
    • @tilaprimera 默认情况下,ListView所有 个实例都有名为 object_list 的变量。但是,您可以在context_object_name 视图类属性中设置特定于当前视图变量名称
    猜你喜欢
    • 2012-03-03
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2016-05-25
    相关资源
    最近更新 更多