Search code examples
djangoblogs

Django template: Displaying parent and child from the same model


I am creating a django blog and I have a Comments model that looks like this:

class Comment(models.Model):
  content = models.TextField('Comment', blank=False, help_text='Comment * Required', max_length=500)
  post = models.ForeignKey('Post', on_delete=models.CASCADE, blank=False, related_name='comments')
  parent = models.ForeignKey('self', null=True, on_delete=models.SET_NULL, related_name='replies')

I am attempting to display the replies below the comment using the code below in the template:

{% for comment in comments %}
  {{ comment.content }}
  {% for reply in comment.replies.all %}
    {{ reply.content }}
  {% endfor %}
{% endfor %}

However, the result of this is the replies get displayed twice. Below the comment they're related to and again by themselves. What am I doing wrong? Why are the replies getting displayed twice. Also, the replies only go one level i.e. there can't be a reply to a reply only a reply to a comment.


Solution

  • You need to do a checking in your template to not display the replies if they have a parent associated to them (since they'll be displayed inside the parent comment). You could do:

    {% for comment in comments %}
      {% if not comment.parent %}
          {{ comment.content }}
          {% for reply in comment.replies.all %}
            {{ reply.content }}
          {% endfor %}
      {% endif %}
    {% endfor %}