Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display multiple views in a Django template?

I want to display the following two views in a template 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]

Is there a way to combine these two views into one view?

How should I get both query sets displayed on index.html?

Is it possible to send all the Item.objects.all() and filter in the template?

like image 811
b3ast Avatar asked Sep 29 '22 18:09

b3ast


1 Answers

A few questions here, let me answer the first.

You can overwrite get_context_data and add to the context of the template for more items in one view. For example...

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 

This way you can include multiple query sets on a page/template as required. In this example moreItems would be available in your template along with popular_items_list

In regards to the second question, yes you can pass in the URL arguments and use them to filter the queryset. I suggest reading up on this.

like image 129
Glyn Jackson Avatar answered Oct 03 '22 00:10

Glyn Jackson