I have a comment table which is having a foreign key to Blog
table. This table is used to make comments to blog and replies can be made to a comment. For this purpose i have used column parent
which will decide to which comment the reply is made.
Now problem is that with object of this table,
comment_obj = comment.objects.filter(blog=blog_obj).order_by("created")
i am not getting the desired output. I want to know as how to display comments and under each comment the replies made to that comment.
Models.py:
class Comment(models.Model):
user = models.ForeignKey(User_info)
blog = models.ForeignKey(Blog)
parent = models.ForeignKey('self', null=True)
comment = models.CharField(max_length=500)
status = models.CharField(max_length=1, default='A')
created = models.DateTimeField(auto_now_add=True)
template:
{% for comment in comment_obj %}
<li>
{{ comment.comment }} - {{ comment.created }}
{% for reply in comment.Comment_set.all %}
<ul>
{{ reply.comment }} - {{ reply.created }}
</ul>
{% endfor %}
</li>
{% endfor %}
But this is not working. Please help. I would like to do this without using any app.
Add related_name using an optional param to the ForeignKey to make things simpler:
class comment(models.Model):
user = models.ForeignKey(User_info)
blog = models.ForeignKey(Blog, related_name='comments')
parent = models.ForeignKey('self', null=True, related_name='replies')
Template: (Assume blog_obj
is the Blog
object)
{% for comment in blog_obj.comments.all %}
{{ comment.comment }}
{% for reply in comment.replies.all %}
{{ reply.comment }}
{% endfor %}
{% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With