简体   繁体   中英

How to add ListView to generic DetailView ? Django

Hi I'm trying to create a portfolio page where I display a list of projects beneath one of the project details. Using generic listview I can display the list of projects.

In my project detail I can use the DetailView to show the project. However I cannot get the list of projects to display in my project detail below the detail.

I extended the base template so the template blocks for the list and projects live in different html files. So I don't think the problems are in my template.

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]

In your ProjectView add this function:

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

This way you can access the list of projects in your template with {{projects}}

Read more here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM