Search code examples
pythondjangocomments

how to add comments to an article in django(Python)?


I'm new to Django, I repeat after the tutorial, but I just can not display comments even from the database in html.

urls.py

static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings

    MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

models.py

from django.db import models
class Post(models.Model):
    photo       = models.ImageField(upload_to='media/photos/',null=True, blank=True)
    name_barber = models.CharField(max_length=30)
    description = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.description[:10]

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    body = models.TextField()
    date_add = models.DateTimeField(auto_now_add=True)


    def __str__(self):
        return '%s - %s' % (self.post, self.name)

html file

} </style>
{% for post in posts %}
<img src="{{MEDIA_URL}}{{post.photo.url}}" width="800"  />

<h3>{{ post.name_barber}}</h3>
<p>{{ post.description}}</p>
{% endfor %}


<h3> Comments.. </h3>

{% 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_add }}
    </strong>
        {{comment.body }}
     {% endfor %}
{% endif %}

after adding a comment through the admin panel, the page displays: no comments yet.. What is the problem please tell me??


Solution

  • Remove the if/else condition and use the {% empty %} tag with your forloop.

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