【发布时间】:2021-01-02 13:07:01
【问题描述】:
我正在尝试创建一个包含两个部分的网页。
- 所有项目的索引列表(始终存在)
- 所选索引项的详细信息
我为同一个模板创建了一个 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