【问题标题】:connecting list view and detail view -django连接列表视图和详细视图 -django
【发布时间】:2020-12-18 13:41:40
【问题描述】:

我正在尝试创建基于类的详细视图,可以通过单击列表视图项来访问它。问题是它在基于函数的视图中很容易实现,但在基于类的视图中却不能这样做。

模型.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 模板工作得很好.. 目录结构很好.. listviw.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 -->

【问题讨论】:

    标签: python django listview django-views detailsview


    【解决方案1】:

    确保目录完好

    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
    

    告诉我它是否有效

    【讨论】:

    • 您说“目录结构很好.. listviw.html 和 detail.html 都在 templates/blog/ 下的同一个文件夹中”所以,更改 template_name = 'blog/blogdetail.html'跨度>
    猜你喜欢
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 2017-04-10
    • 2020-10-30
    • 2012-01-09
    • 1970-01-01
    相关资源
    最近更新 更多