[英]Django: setting multiple lists in a view for a template to iterate over
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. 我试图在视图中创建多个上下文对象,以便可以在模板中分别对其进行迭代,并将它们垂直打印为HTML列表。 How can I achieve this?
我该如何实现?
My code is something like this: 我的代码是这样的:
views.py: 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: 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. 我知道,多个
context_object_name
的东西不起作用,但我将其放在其中以演示我想要的东西。
Simply, you can send three different list in context like this. 简单来说,您可以在这样的上下文中发送三个不同的列表。 Is there any speical reason to use ListView for sending three lists?
使用ListView发送三个列表是否有特殊原因?
from django.views import View
class MultiListView(View):
def get(self, request, *args, **kwargs):
list1 = List.objects.filter(something)
list2 = List.objects.filter(something)
list3 = List.objects.filter(something)
return render(request, 'list.html', {'list1':list1, 'list2':list2, 'list3':list3})
How about using Functional-based View
? 如何使用
Functional-based View
? NOT Class-based View
. 不是
Class-based View
。 It will be easy if you use this. 如果使用它,将很容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.