Django: setting multiple lists in a view for a template to iterate over

Viewed 1597

I'm trying to create multiple context objects in a view so that I can iterate over them separately in the template and print them vertically as HTML lists. How can I achieve this?

My code is something like this:

views.py:

class MultiListView(ListView):

    template_name = os.path.join(APPNAME, "list.html")
    context_object_name = 'list1'
    context_object_name2 = 'list2'
    context_object_name3 = 'list3'

    def get_queryset(self):

        query_set = List.objects.all()
        return list(query_set) # Only sets the context_object_name var, not the rest

list.html:

{% if list1 %}
  <ul>
   {% for item in list1 %}
    <li class="item-list">item.name</li>
   {% endfor %}
  </ul>
{% endif %}

{% if list2 %}
  <ul>
   {% for item in list2 %}
    <li class="item-list">item.name</li>
   {% endfor %}
  </ul>
{% endif %}
{% if list3 %}
  <ul>
   {% for item in list3 %}
    <li class="item-list">item.name</li>
   {% endfor %}
  </ul>
{% endif %}

The important thing for me is that the lists are printed vertically, so each list is it's own column. I am aware that the multiple context_object_name's thing won't work, but I put it in there to demonstrate what I want.

2 Answers
Related