Home > Back-end >  My django generic DetailView doens't show any data
My django generic DetailView doens't show any data

Time:10-04

Hello everyone I have just started developing my blog with django but I don't get to display my posts individually. DetailView doesn't work, please help!

here is my url

from django.urls import path
from .views import Home, ArticleDetailView


urlpatterns = [
    path('', Home.as_view(), name='home'),
    path('article/<int:pk>', ArticleDetailView.as_view(), name='article_details'),
]

Here is my view.

from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Article

# Create your views here.
class Home(ListView):
    model = Article
    template_name = 'home.html'

class ArticleDetailView(DetailView):
    model = Article
    template_name = 'article_detail_view.html'

My model

from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class Article(models.Model):
    title = models.CharField(max_length=255)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()

    def __str__(self):
        return self.title   '|'   str(self.author)

    class Meta:
        verbose_name = 'Article'
        verbose_name_plural = 'Articles'

Home.html

 <h2>Post</h2>
<ul>
    {% for post in object_list %}
        <li><a href="{% url 'article_details' post.pk %}">{{post.title}} by {{ post.author }}</a></br>
        <p>{{post.body}}</p></li>
    {% endfor %}
    
</ul>

article_detail_view.html

<h2>Article Detail View</h2>

<h2>{{post.title}} By {{ post.author }}</h2></br>
<p>{{post.body}}</p>

CodePudding user response:

Thanks for updating the question.

First add the get_absolute_url method to the model as follows:

class Article(models.Model):
    title = models.CharField(max_length=255)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()

    def __str__(self):
        return self.title   '|'   str(self.author)

    class Meta:
        verbose_name = 'Article'
        verbose_name_plural = 'Articles'
        
    def get_absolute_url(self):
        return reverse("article_details", kwargs={"pk": self.pk})

In your article_detail_view.html, you can access the article using the article instance:

<h2>Article Detail View</h2>

<h2>{{article.title}} By {{ article.author }}</h2></br>
<p>{{article.body}}</p>

CodePudding user response:

in your article_detail_view.html you can access the article by: {{object.title}} you can also specify what to return in template and how you wanna name it by overriding get_context_data check this

CodePudding user response:

in models.py

class Meta:
    managed = True
    verbose_name = 'Article'
    verbose_name_plural = 'Articles'
  • Related