Tudor Nicolescu
Tudor Nicolescu

Reputation: 39

Django template cannot see model object

models.py

from django.db import models
from django.urls import reverse
# Create your models here.
class Post(models.Model):
    title = models.CharField(max_length=256)
    author = models.CharField(max_length=256)
    coverphoto_link = models.CharField(max_length=1000, blank=True)
    text = models.TextField()
    photo_link = models.CharField(max_length=1000,blank=True)
    date = models.DateTimeField(auto_now_add=True) 
    def get_absolute_url(self):
        return reverse("basic_app:article", kwargs = {'pk':self.pk})

class Comment(models.Model):
    post =  models.ForeignKey(Post,related_name='comments', on_delete = models.CASCADE)
    name = models.CharField(max_length=300)
    body = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return self.name

article.html

{% include 'base1.html' %}
{% load static %}
<br>
<div class="container" id='container_article'>
    <div class="container2">
        <h1>{{ article_detail.title }}</h1>
    <p class="author_detail" style="color: rgb(0, 4, 255);">{{ article_detail.author }} | {{article_detail.date }}</p>
    <br>
    <img  id="photo" src="{{ article_detail.photo_link }}">
    </div>
    
    <p id="articletext">{{ article_detail.text }}</p>
    <br>
    <br>
    <hr>
<!--- HERE --->
    <h2>Comments...</h2>
    {% if not post.comments.all %}
        No comments yet...<a href="#">Add one</a>
    {% else %}
    
    {% for comment in post.comments.all %}
    <strong> {{ comment.name }} - {{ comment.date_added }}</strong>
    <br>
    {{ comment.body }}
    <br>
    {% endfor %}
    <hr>
    {% endif %}

</div>
{% include 'footer.html' %}



THe main problem is that I created comments at the admin secction, all good, but the page is still displaying "No comments yet...".See the <!--- HERE ---> part, there is the problem.I also registered the app and the model at admin.py.

Upvotes: 0

Views: 24

Answers (1)

Ffion
Ffion

Reputation: 559

I would ty this instead:

{% for comment in post.comments.all %}
    <strong> {{ comment.name }} - {{ comment.date_added }}</strong>
    <br>
    {{ comment.body }}
    <br>
{% empty %}
    No comments yet...<a href="#">Add one</a>
{% endfor %}

I don't think this is correct:

{% if not post.comments.all %}

Upvotes: 2

Related Questions