aryaman choudhary
aryaman choudhary

Reputation: 11

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

Upvotes: 1

Views: 192

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

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

{% for cmnts in post.postcomments.all %}
    …
{% 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 ModelForms by default.

Upvotes: 1

Related Questions