您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Django将多个模型传递给一个模板

Django将多个模型传递给一个模板

我建议你删除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"
        ),
Go 2022/1/1 18:23:33 有319人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶