connecting list view and detail view -django

Viewed 307

i am trying to create class based detailed view, which can be accessed by clicking listview items.. the problem is it was easly achieved in function based views but cant do the same in class based views.

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 template is working absolutely fine.. the directory structure is fine.. both listviw.html and detail.html are in same folder under templates/blog/ ..

listview template

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

Make sure directories are good

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

Add this

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

Tell me if it worked or not

Related