如何在Django模板中显示多个视图?

时间:2014-09-29 21:17:48

标签: python django django-templates django-views

我想在模板index.html中显示以下两个视图。

class IndexView(generic.ListView):

    template_name = 'items/index.html'
    context_object_name = 'popular_items_list'

    def get_queryset(self):
        return Item.objects.order_by('-rating')[:5]

class tryView(generic.ListView):

    template_name = 'items/index.html'
    context_object_name = 'latest_items_list'

    def get_queryset(self):
        return Item.objects.order_by('pub_date')[:5]

有没有办法将这两个视图合并到一个视图中?

如何在index.html上显示两个查询集?

是否可以在模板中发送所有Item.objects.all()和过滤器?

2 个答案:

答案 0 :(得分:5)

这里有几个问题,让我回答第一个问题。

您可以覆盖get_context_data并在一个视图中添加模板的上下文以获取更多项目。例如......

class IndexView(generic.ListView):
   template_name = 'items/index.html'
   context_object_name = 'popular_items_list'

   def get_queryset(self):
     return Item.objects.order_by('-rating')[:5]

   def get_context_data(self, *args, **kwargs):
       context = super(IndexView, self).get_context_data(*args, **kwargs)
       context['moreItems'] = Item.objects.order_by('pub_date')[:5]
       return context 

这样,您可以根据需要在页面/模板上包含多个查询集。在此示例中,您的模板中将提供moreItems以及popular_items_list

关于第二个问题,是的,您可以传入URL参数并使用它们来过滤查询集。我建议阅读这篇文章。

答案 1 :(得分:-1)

我可以想到两种选择。一个选项是视图中的get_context_data,其外观如下:

#views.py
class IndexView(generic.ListView):

    template_name = 'items/index.html'

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['item_by_rating'] = Item.objects.order_by('-rating')[:5]
        context['item_by_pub_date'] = Item.objects.order_by('pub_date')[:5]
        return context

然后在您的模板中,您可以访问{{items_by_rating}}和{{items_by_pub_date}}

第二个选项是对模板中的对象进行排序,这样您就可以在视图中定义一个上下文变量,然后使用the dictsort template filter在模板中以不同的方式进行排序。这看起来像这样:

# views.py
class tryView(generic.ListView):

    template_name = 'items/index.html'

    def get_queryset(self):
        return Item.objects.all()

# index.html
{% for i in object_list|dictsort:"item.pub_date" %}
    {{ i.rating }} {{ i.pub_date }}
{% endfor %}

我想我更喜欢第二个选项,只是传递一个object_list上下文项,然后在模板中进行排序。但无论哪种方式都应该没问题。

相关问题