如何在 django(Python) 中为文章添加评论?

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

我是 Django 的新手,我在教程之后重复了一遍,但我什至无法显示来自 html 中的数据库的评论。

urls.py

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

设置

    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 文件

} </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 %}

通过管理面板添加评论后,页面显示:还没有评论.. 请问有什么问题吗??

删除 if/else 条件并在 forloop 中使用 {% empty %} 标签。

 {% 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 %}