简体   繁体   中英

Comment section in django blog won't show up under each individual post?

The comment successfully saves in the django admin but won't show up on the actual site.

Here is the comment model:

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)

This the html code for the blog home. the post for loop goes through all the post objects and prints them out. I created a comment loop to loop through all the comments for the linked post and print. Is the problem in my html code?

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

The Post object is named post in the {% for post in posts %} loop, so you access the comments with:

{% for cmnts in postcomments %}
    …
{% endfor %}

Note : Models in Django are written in PerlCase , not snake_case , so you might want to rename the model from comment to Comment .


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 : Django's DateTimeField [Django-doc] has a auto_now_add=… parameter [Django-doc] to work with timestamps. This will automatically assign the current datetime when creating the object, and mark it as non-editable ( editable=False ), such that it does not appear in ModelForm s by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM