S
S
s_katala2018-06-06 08:32:46
Django
s_katala, 2018-06-06 08:32:46

How to display MMTP tree comments?

model.py

from django.db import models
from posts.models import Post
from django.utils import timezone
from django.conf import settings
from mptt.models import MPTTModel, TreeForeignKey

class Comment(MPTTModel):
  post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
  author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
  content = models.TextField()
  date_add = models.DateTimeField(default=timezone.now)
  approved_comment = models.BooleanField(default=False)
  parent = TreeForeignKey('self', related_name='children',null=True, blank=True, db_index=True, on_delete=models.CASCADE)

  class MPTTMeta:
    order_insertion_by = ['content']

  def approve(self):
    self.approved_comment = False
    self.save()

  def get_absolute_url(self):
    return reverse('post', kwargs={'slug': self.slug})

  def __str__(self):
    return self.content

views.py
from django.shortcuts import render
from comments.forms import CommentForm
from posts.models import Post
from django.http import HttpResponseRedirect
from django.urls import reverse

def add_comment(request, slug):
  if request.method == 'POST':
    comment_form = CommentForm(data=request.POST)
    if comment_form.is_valid():
      comment = comment_form.save(commit=False)
      comment.post = Post.objects.get(slug=slug)
      comment.author = request.user
      comment.save()
  return HttpResponseRedirect(reverse('posts:fullstory', kwargs={'slug': slug}))

forms.py
from django import forms
from comments.models import Comment

class CommentForm(forms.ModelForm):
  class Meta():
    model = Comment
    fields = ('content',)

  def __init__(self, *args, **kwargs):
    super(CommentForm, self).__init__(*args, **kwargs)
    self.fields['content'].label = ""

How to display and add a reply in a template?
Help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-06-06
@s_katala

Example from documentation :

<ul class="root">
    {% recursetree comments %}
        <li>
            {{ node.content }}
            {% if not node.is_leaf_node %}
                <ul class="children">
                    {{ children }}
                </ul>
            {% endif %}
        </li>
    {% endrecursetree %}
</ul>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question