How Do I create a nested comment section?

Viewed 33

hat is the best way to create a nested comment section?

My current Views is setup is

class AddCommentView(CreateView):
    model = Comment
    form_class = CommentForm
    template_name = 'add_comment.html'

    # fields = '__all__'
    def form_valid(self, form):
        form.instance.post_id = self.kwargs['pk']
        return super().form_valid(form)

    success_url = reverse_lazy('home')

This is my current models is..


class Comment(models.Model):
    post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
    name = models.CharField(max_length=250)
    body = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s - %s' % (self.post.title, self.name)

Any help on this would be greatly appreciated!

1 Answers

You need self-joined model to achieve this.

django-mptt ( Modified Preorder Tree Traversal) can be used for this purpose.

Assuming comment can be a response to a Post or to another comment something like

Post
Comment
   Comment
Comment
   Comment
   Comment
     Comment
  

this video is actually what you are looking for.

Learn Django 3 - Build MPTT Comments

Related