Django - 对象列表在DetailView中不可见。

问题描述 投票:0回答:1

我的主页上有帖子列表,这些帖子是帖子详细视图的链接。链接工作正常,但当我进入DetailView时,列表就不可见了--我必须回到主页选择其他帖子。显示帖子列表的元素位于base.html,正确地将对象列表传到home.html,而在post_detail.html中列表是空的。

主页是这样的

帖子详细视图是这样的--帖子列表不可见了。

在主页上查看

在DetailView上的不ect视图--ul元素为空。

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
python django django-views django-templates django-urls
1个回答
0
投票

你必须覆盖你的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
© www.soinside.com 2019 - 2024. All rights reserved.