Search code examples
htmldjangodjango-modelsdjango-class-based-viewsdetailsview

class based detail view is not returning the template


In my article_details.html page I have written {{post.title}} but my the page is not showing the specific title. My app name is post and the model name is BlogPost. this is my views.py:

from django.shortcuts import render
from .models import *
from .forms import *
from django.views.generic import ListView,CreateView
from django.views.generic.detail import DetailView
def home(request):
return render(request,'post/home.html')

class HomeView(ListView):
      model = BlogPost
      template_name = "post/home2.html"

class ArticleDetailView(DetailView):
           model = BlogPost
          template_name = "post/article_details.html"
class AddPostView(CreateView):
    model = BlogPost
    template_name = "post/add_post.html"
    fields = '__all__'

this is my urls.py

from post import views
from django.urls import path
from .views import HomeView,ArticleDetailView,AddPostView
app_name = 'post'
urlpatterns = [
         path('',views.home,name="home"),
         path('home2/',HomeView.as_view(),name = "home2"),
         path('article/<int:pk>',ArticleDetailView.as_view(),name = "article-details"),
         path('add_post/',AddPostView.as_view(),name="add_post"),
    ]

this is my list page: post/home2.html

<ul>
{%for post in object_list %}
    <li><a href="{%url 'post:article-details' post.pk %}">{{post.title}}</a>-{{post.author}}<br/>
     {{post.body}}</li>
{%endfor%}
 </ul>

and this is my detail page:article_details.html:

<h1>{{post.title}}</h1>
<small>by:{{post.author}}</small><br/>
<hr>
<br/>
<p>{{post.body}}</p>



enter code here

Solution

  • Unless you define context_object_name, the view will send the object via context perameter of your model name in all lower case. So you should get value via {{ blogpost.author }}. Or, you can update your view like:

    class ArticleDetailView(DetailView):
          model = BlogPost
          template_name = "post/article_details.html"
          context_object_name = 'post'
    

    Please see the documentation on context object naming for more details.