我希望能够在同一个页面或Django模板上渲染、显示或访问列表视图和细节视图。下面是我目前为止的尝试。这里是一个链接,我在那里得到了一个非常相似但有限的代码来解决这个问题。(DJANGO: How to access data from ListView and DetailView on the same template?)
结果当我runserver.py显示一个完全空白的页面,没有一个错误,甚至在终端上请帮助我解决这个问题。
models.py
class Reports(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
title = models.CharField(max_length=255)
name = models.CharField(max_length=255)
email = models.EmailField(max_length = 254)
phone = models.CharField(max_length=11)
address = models.CharField(max_length=255, blank=True, null=True)
subject = models.CharField(max_length=255)
message = models.TextField(blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
due = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True)
def __str__(self):
return self.name
class Meta:
ordering = ('-created',)
views.py
from django.shortcuts import render, redirect
from django.views.generic import TemplateView
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from datetime import timezone, tzinfo
from . models import Reports
# Create your views here.
class index(TemplateView):
template_name = 'reports_list.html'
class ReportsListView(ListView):
model = Reports
# context_object_name = 'data'
def get_queryset(self):
return Reports.objects.filter(create_date__lte=timezone.now()).order_by('-create_date')
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
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.name }}
</div>
<div class="read-content">
{{reports.message}}
</div>
{% endblock %}
urls.py
from django.urls import path
from . import views
from . views import index, Detail
urlpatterns = [
path('', index.as_view(), name='index'),
# path('Detail/<int:pk>/', Detail.as_view(), name='contact_detail'),
]
1条答案
按热度按时间r8uurelv1#
我使用了一个详细信息/单个页面类别和类别名称/标题来实现这一点,并将它们呈现在同一个模板中。它确实工作得很好,现在一个URL/模板将两个类别名称(显示所有类别名称/标题)作为侧菜单提供服务,而详细信息页面呈现一个项目