我的主页上有帖子列表,这些帖子是帖子详细视图的链接。链接工作正常,但当我进入DetailView时,列表就不可见了--我必须回到主页选择其他帖子。显示帖子列表的元素位于base.html,正确地将对象列表传到home.html,而在post_detail.html中列表是空的。
base.html
<body>
<div>
<ul>
<li>
<a href="{% url 'blog-home' %}"> home</a>
</li>
<li>
<a> items</a>
<ul>
{% for post in posts %}
<li>
<a href="{% url 'post-detail' post.id %}"> {{ post.title }}</a>
</li>
{% endfor %}
</ul>
</li>
</ul>
</div>
<di>
{% block content %}
{% endblock content %}
</div>
</body>
首页.html
{% extends "blog/base.html" %}
{% block content %}
{% for post in posts %}
<div>
<a href="#">{{post.title}}</a>
<p>{{post.content}}</p>
<p>{{post.date_posted}}</p>
</div>
{% endfor %}
{% endblock content %}
post_detail.html
{% extends "blog/base.html" %}
{% block content %}
<div>
<a href="#">{{object.title}}</a>
<p>{{object.content}}</p>
</div>
{% endblock content %}
urls.py
from django.urls import path
from .views import PostListView, PostDetailView
from . import views
urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
]
视图.py
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
class PostDetailView(DetailView):
model = Post
模型.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
def __str__(self):
return self.title
你必须覆盖你的DetailView的上下文,它只显示当前实例的数据。
class PostDetailView(DetailView):
model = Post
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['other_posts'] = Post.objects.all()
return context