Answer the question
In order to leave comments, you need to log in
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
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}))
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 = ""
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question