Detail view is not displaying content of models

Question:

My detail View in Django, isn’t successfully displaying the content selected from the listviews. The following is my code.

Models.py:

from django.db import models

from django.contrib.auth.models import User

# Create your models here.
class Post_Model(models.Model):

    Title = models.CharField(max_length=50)
    Author = models.ForeignKey(User, on_delete=models.CASCADE)
    Body = models.TextField()

    def __str__(Self):
        return Self.Title + ' | ' + str(Self.Author)

urls.py:

from django.urls import path
from .views import Article_details, Home_page

urlpatterns = [
    path('', Home_page.as_view(), name="Home"),
    path('Article/<int:pk>/', Article_details.as_view(), name="Article"),

Views.py:

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

class Home_page(ListView):
    model = Post_Model
    template_name = 'June11App/Home.html'

class Article_details(DetailView):
    model = Post_Model
    template_name = 'June11App/Article.html'

Html list view:

    <h1>Home Page</h1>
<ul>
    {% for Post in object_list %}
<li>
    <a href="{% url 'Article' Post.pk  %}"> 
        {{Post.Title}} 
    </a>
    - {{Post.Author}}<br>
    {{Post.Body}}
</li>
<br>
    {% endfor %}
</ul>

Html detail view:

<h1>Article Page</h1><br>

{{Post.Author}}
{{Post.Body}}

I hope my query made sense. I don’t receive any error on myside, its just not working as it should.

Asked By: Mirca Gardenman

||

Answers:

The object data is passed as object and post_model, not Post, so:

<h1>Article Page</h1><br>

{{ object.Author }}
{{ object.Body }}

Note: Models normally have no …Model suffix. Therefore it might be better to rename Post_Model to Post.


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.


Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be: author instead of Author.

Answered By: Willem Van Onsem