我正在建立一个包括条目之间关系的通讯簿。我为个人,公司,场地和角色有单独的模型。在我的索引页面上,我想列出每个模型的所有实例,然后对其进行过滤。这样一个人可以轻松地搜索和查找条目。我已经能够使用通用视图列出单个模型,并使用get_extra_context显示另一个模型:
#views.py class IndividualListView(ListView): context_object_name = "individual_list" queryset = Individual.objects.all() template_name='contacts/individuals/individual_list.html' class IndividualDetailView(DetailView): context_object_name = 'individual_detail' queryset = Individual.objects.all() template_name='contacts/individuals/individual_details.html' def get_context_data(self, **kwargs): context = super(IndividualDetailView, self).get_context_data(**kwargs) context['role'] = Role.objects.all() return context
我还可以使用自定义视图列出单个模型:
#views.py def object_list(request, model): obj_list = model.objects.all() template_name = 'contacts/index.html' return render_to_response(template_name, {'object_list': obj_list})
这是这两个测试的urls.py:
(r'^$', views.object_list, {'model' : models.Individual}), (r'^individuals/$', IndividualListView.as_view(), ), (r'^individuals/(?P<pk>\d+)/$', IndividualDetailView.as_view(), ),
所以我的问题是“如何修改此参数以将更多模型传递给模板?” 可能吗 关于StackOverflow的所有类似问题仅询问两个模型(可以使用get_extra_context解决)。
我建议你删除object_list视图,
object_list
为此特定视图定义字典,
all_models_dict = { "template_name": "contacts/index.html", "queryset": Individual.objects.all(), "extra_context" : {"role_list" : Role.objects.all(), "venue_list": Venue.objects.all(), #and so on for all the desired models... } }
然后在你的网址中:
#add this import to the top from django.views.generic import list_detail (r'^$', list_detail.object_list, all_models_dict),
我最终修改了@thikonom的答案以使用基于类的视图:
class IndexView(ListView): context_object_name = 'home_list' template_name = 'contacts/index.html' queryset = Individual.objects.all() def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['roles'] = Role.objects.all() context['venue_list'] = Venue.objects.all() context['festival_list'] = Festival.objects.all() # And so on for more models return context
并在我的urls.py中
url(r'^$', IndexView.as_view(), name="home_list" ),