@s_katala

Как отобразить древовидные комментарии MMTP?

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 = ""


Как в шаблоне вывести и дописать reply?
Help
  • Вопрос задан
  • 433 просмотра
Решения вопроса 1
sergey-gornostaev
@sergey-gornostaev Куратор тега Django
Седой и строгий
Пример из документации:
<ul class="root">
    {% recursetree comments %}
        <li>
            {{ node.content }}
            {% if not node.is_leaf_node %}
                <ul class="children">
                    {{ children }}
                </ul>
            {% endif %}
        </li>
    {% endrecursetree %}
</ul>
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы