Amir Khorasani
Amir Khorasani

Reputation: 170

how to create comment tree in django

I need a comment system so can reply a comment to any comment

I know how to write models and views and my only problem is showing them in the template

For example, maybe a group of comments are like this:

comment
    comment
        comment
        comment
    comment
    comment
        comment
            comment
comment
    comment

How can I display this structure in the template?

Upvotes: 0

Views: 419

Answers (1)

Mojtaba Arezoomand
Mojtaba Arezoomand

Reputation: 2380

Your Comment model should have a parent field which refers to another comment(self relationship).
it will be something like this, add it to your Comment model:

parent = models.ForeignKey('self', null=True, blank=True, related_name='replies')  

now you have your replies and even your replies can be the parent of another comment.
And in your template:

{% for replay in comment.replies.all %}
    <p class="info">{{ replay.user }} | {{ replay.date }}</p>
    <li>{{ replay.text }}</li>
{% endfor %}  

Note that the field names are just examples

Upvotes: 1

Related Questions