【问题标题】:Comment section in django blog won't show up under each individual post?django 博客中的评论部分不会显示在每个单独的帖子下?
【发布时间】:2020-10-11 19:16:20
【问题描述】:

评论成功保存在 django 后台,但不会显示在实际网站上。

这是评论模型:

class comment(models.Model):
    linkedpost = models.ForeignKey(Post, related_name="postcomments", on_delete=models.CASCADE)
    commentauthor = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField(max_length=100)
    date_posted = models.DateTimeField(default=timezone.now)

这是博客主页的 html 代码。 post for 循环遍历所有 post 对象并将它们打印出来。我创建了一个评论循环来遍历链接帖子的所有 cmets 并打印。是不是我的html代码有问题?

{% for post in posts %}
    <article class="media content-section">
        <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
      <div class="media-body">
        <div class="article-metadata">
          <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
          <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
        </div>
        <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
        <p class="article-content">{{ post.content }}</p>
        <div>
            <h2>Comments</h2>
            {% for cmnts in linkedpost.postcomments %}
                #<a class="mr-2" href="{% url 'user-posts' cmnts.author.username %}">{{ cmnts.commentauthor }}</a>
                <small class="text-muted">{{ cmnts.date_posted|date:"F d, Y" }}</small>
                <p class="article-content">{{ cmnts.body }}</p>
            {% endfor %}
        </div>
      </div>
    </article>
{% endfor %}

【问题讨论】:

  • 应该是{% for cmnts in post.postcomments.all %}

标签: python html django blogs


【解决方案1】:

Post 对象在 {% for post in posts %} 循环中被命名为 post,因此您可以通过以下方式访问 cmets:

{% for cmnts in post.postcomments.all %}
    …
{% endfor %}

注意:Django 中的模型是用 PerlCase 编写的,而不是 snake_case, 因此您可能需要将模型从 comment 重命名为 Comment


注意:通常使用settings.AUTH_USER_MODEL [Django-doc] 引用用户模型比直接使用User model [Django-doc] 更好。更多信息可以查看referencing the User model section of the documentation


注意:Django 的DateTimeField [Django-doc] 有一个auto_now_add=… parameter [Django-doc] 使用时间戳。这将自动分配当前日期时间 创建对象时,将其标记为不可编辑(editable=False),例如 默认不会出现在ModelForms 中。

【讨论】:

    猜你喜欢
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 2013-08-27
    • 2021-04-16
    相关资源
    最近更新 更多