如何将 ListView 添加到通用 DetailView ?姜戈

How to add ListView to generic DetailView ? Django

您好,我正在尝试创建一个投资组合页面,我在其中一个项目详细信息下方显示项目列表。使用通用列表视图,我可以显示项目列表。

在我的项目详细信息中,我可以使用 DetailView 来显示项目。但是,我无法在详细信息下方的项目详细信息中显示项目列表。

我扩展了基本模板,因此列表和项目的模板块位于不同的 html 文件中。所以我认为问题不在我的模板中。

views.py

class ProjectView(generic.DetailView):
      template_name = 'portfolio/project_detail.html'

      def get_queryset(self):
          return Project.objects.filter(pub_date__lte=timezone.now())
class IndexView(generic.ListView):
      template_name = 'portfolio/index.html'
      context_object_name = 'project_list'

      def get_queryset(self):
           return Project.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')

urls.py

urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),,
    url(r'^project/(?P<pk>[0-9]+)/$', views.ProjectView.as_view(), name='project]

在您的 ProjectView 中添加此函数:

def get_context_data(self, **kwargs):
    context = super(ProjectView , self).get_context_data(**kwargs)
    context['projects'] = Project.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')
    return context

这样您就可以使用 {{projects}}

访问模板中的项目列表

阅读更多here