DJANGO:如何在同一模板上访问 ListView 和 DetailView 的数据?

DJANGO: How to access data from ListView and DetailView on the same template?

我正在尝试创建一个包含两部分的网页。

  1. 所有项目的索引列表(始终存在)
  2. 所选索引项的详细信息

我为此创建了一个 LIST VIEW 和一个 DETAIL VIEW,但问题是不能在同一个模板上调用这两个视图.

我试着列出了'reports_list.html'中的所有项目,然后将这个模板继承到'report_detail.html'中去查看索引列表是否保留但没有。

有办法做到这一点吗?

代码:

views.py

from django.shortcuts import render
from django.views.generic import TemplateView, DetailView, ListView
from .models import Reports
from django.utils import timezone

class index(TemplateView):
    template_name = 'reports_list.html'

class ReportsListView(ListView):
    model = Reports

    def get_queryset(self):
        return Reports.objects.filter(create_date__lte=timezone.now()).order_by('-create_date')

class Detail(DetailView):
    model = Reports

 

reports_list.html

<ul class="index-list">
    
    {% for report in reports_list %}
        
        <li data-id= {{ report.pk }}>
            <a class="index-link" href="{% url 'reports:reports_detail' pk=report.pk %}">
                <span class="index-name">{{report.title}}</span>
            </a>
         </li> 

     {% endfor %}

</ul>

report_detail.html

{% extends './reports_list.html' %}

{% block contentblock %}
    <h1>THIS IS DETAIL VIEW</h1>
    
    <div class="read-header">
        <div class="read-title">
            {{ reports.title }}
        </div>
    </div>
    
    <div class="read-subtitle">
        {{ reports.subtitle }}
    </div>

    <div class="read-content">
        {{reports.content}}
    </div>  
{% endblock %}

您所要做的就是将额外的上下文数据传递给 DetailView 以供列表查看,因为您要在此处扩展模板。 Docs

class Detail(DetailView):
    model = Reports

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        # Add in the reports list to context
        context['reports_list'] = Reports.objects.filter(create_date__lte=timezone.now()).order_by('-create_date')
        return context