djangodjango-templatestemplate-inheritance

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


I am trying to create a webpage which has two parts.

  1. An index list of all items (that persists throughout)
  2. Detail of the selected index item

I created a LIST VIEW and a DETAIL VIEW for the same but the problem is both views cannot be called on the same template.

I tried to list all the items in 'reports_list.html' and then inherit this template to 'report_detail.html' to see if the index list stays but it doesn't.

Is there a way to accomplish this?

CODE:

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 %}

Solution

  • All you have to do is pass additional context data to DetailView for the list to see since you are extending the template here. 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