【问题标题】:Can I have multiple lists in a Django generic.ListView?我可以在 Django generic.ListView 中有多个列表吗?
【发布时间】:2013-09-15 12:42:39
【问题描述】:

作为一名 Django 初学者,我正在学习由 django docs 在https://docs.djangoproject.com/en/1.5/intro/tutorial04/提供的教程

在其中,他们展示了使用按发布日期进行查询列出的多个民意调查列表。我可以添加另一个列表,也可以在要使用的模板中使用。示例 在同一页面上按日期显示最新民意调查列表,并按字母顺序显示另一个。

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_poll_list'

    def get_queryset(self):
        """Return the last five published polls."""
        return Poll.objects.order_by('-pub_date')[:5]

【问题讨论】:

    标签: django django-views


    【解决方案1】:

    当然,您只需要编写自己的“get_context_data”方法来检索这些值,然后它们将在视图中可用。类似的东西:

    def get_context_data(self, *args, **kwargs):
        context = super(IndexView, self).get_context_data(*args, **kwargs)
        context['alphabetical_poll_list'] = Poll.objects.order_by('name')[:5]
        return context 
    

    这样,{{ latest_poll_list }} 和 {{ alphabetical_poll_list }} 都可以在您的模板中使用。

    【讨论】:

    • 只是要注意这个追加变量到模板上下文,所以原来的get_querysetcontext_object_name应该保持在原来的IndexView
    猜你喜欢
    • 1970-01-01
    • 2012-07-12
    • 2012-04-03
    • 2012-05-25
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    相关资源
    最近更新 更多