【问题标题】:DJANGO: How to access data from ListView and DetailView on the same template?DJANGO:如何从同一模板上的 ListView 和 DetailView 访问数据?
【发布时间】:2021-01-02 13:07:01
【问题描述】:

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

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

【问题讨论】:

  • 是的,使用模板标签{% extends "reports_list.html" %},所以可以使用单个视图的上下文来填充两个模板
  • @Jonas 我知道我们可以重用“reports_list.html”中的代码结构。问题是当我将“reports_list.html”继承到“report_detail.html”时,我丢失了添加到“reports_list.html”的报告列表
  • 分享相关代码。视图和模板。
  • @AchuthVarghese 添加了

标签: django django-templates template-inheritance


【解决方案1】:

您所要做的就是将额外的上下文数据传递给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

【讨论】:

  • 看来我应该花更多时间阅读文档!这次真是万分感谢。它有效?
猜你喜欢
  • 2021-05-30
  • 1970-01-01
  • 2020-03-06
  • 2017-05-08
  • 2011-04-23
  • 1970-01-01
  • 2013-11-15
  • 1970-01-01
  • 2010-12-25
相关资源
最近更新 更多