连接 Django 中的列表视图和详细视图

3

我正在尝试创建基于类的详细视图,可以通过单击列表视图项目访问。 问题在于,使用函数视图很容易实现,但是在基于类的视图中无法做到同样的效果。

model.py

from django.db import models
import datetime
  # Create your models here.
   class BlogPost(models.Model):


title = models.CharField(max_length=500)
writer = models.CharField(max_length=150,default='my dept')
category =models.CharField(max_length=150)
image = models.ImageField(upload_to='images')
post   = models.TextField(max_length=2000)
Date  = models.DateField( default=datetime.date.today)


def __str__(self):
    return self.title

views.py

     from.models import BlogPost , EDITORIAL_RESPONSIBILITIES , Reviewers ,Confrences 
             ,ABSTRACT_IN_CONFERENCES
    class BlogList(ListView):
       model = BlogPost
      template_name = 'blog/bloglist.html'
         context_object_name = 'post'
   class BlogDetail(DetailView):
       model = BlogPost
          template_name = 'blogdetail.html'

urls.py

path('list', BlogList.as_view(), name='list'),
path('(?P<id>\d+)/', BlogDetail.as_view())

listview模板运行得非常好。目录结构良好。listview.html和detail.html都在templates/blog/同一个文件夹下。

<div class="post-body">
                        {% for p in post %}
                        <blockquote>{{p}}</br></br>{{p.Date}}</blockquote>
                        {% endfor %}
                    </div><!-- end post-body -->
1个回答

0

确保目录正确无误

templates
   --blog
     ---bloglist.html
     ---blogdetail.html

添加这个

class BlogDetail(DetailView):
   model = BlogPost
   template_name = 'blog/blogdetail.html'

def get_context_data(self, *args, **kwargs):
    context = super(BlogDetail, self).get_context_data(*args, **kwargs)
    post = self.get_object()
    context["post"] = post
    print(post)  #//To check if it's returning the right post
    return context

告诉我它是否起作用了


你说:“目录结构没问题...listview.html和detail.html都在templates/blog/文件夹下的同一文件夹中。” 所以,请将template_name更改为'blog/blogdetail.html'。 - noob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接