2014-09-29 42 views
4

我想在模板index.html中顯示以下兩個視圖。如何在Django模板中顯示多個視圖?

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()和過濾器?

回答

4

這裏有幾個問題,讓我回答第一個問題。

您可以覆蓋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參數並使用它們來過濾queryset。我建議閱讀這個。

+0

非常感謝。 – b3ast 2014-09-30 17:32:57

-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中的上下文項,然後在模板排序。但無論哪種方式應該沒問題。