我正在开发简单的博客,我正在尝试为每个帖子实现嵌套评论系统。
我创建了评论模型,它可以通过Django Admin Page正常工作。
我不知道如何创建用于发布新评论和回复的表单。
以下是我目前的情况:
models.py
(...)
class Post(models.Model):
author = models.ForeignKey('Author', on_delete=models.CASCADE)
title = models.CharField(max_length=250)
slug = models.SlugField(unique=True, blank=True, max_length=250)
created = models.DateTimeField(auto_now=False, auto_now_add=True)
modified = models.DateTimeField(auto_now=True, auto_now_add=False)
tags = TaggableManager(blank=True)
image = models.ImageField(upload_to="images/%Y/%m/", blank=True, null=True)
content = models.TextField()
def get_absolute_url(self):
return reverse('post_detail', kwargs={'slug': self.slug, })
# create slug
def save(self, *args, **kwargs):
if not self.id:
self.slug = slugify(unidecode(self.title))
super(Post, self).save(*args, **kwargs)
def __str__(self):
return str(self.title)
class Comment(MPTTModel):
post = models.ForeignKey("Post", on_delete=models.CASCADE, null=True, related_name='comments')
parent = TreeForeignKey('self', null=True, blank=True, related_name='replies', db_index=True)
name = models.CharField(max_length=250)
email = models.EmailField(max_length=250, blank=True, null=True)
website = models.CharField(max_length=250, blank=True, null=True)
created = models.DateTimeField(auto_now=False, auto_now_add=True)
content = models.TextField()
def __str__(self):
return str("{}: {}...".format(self.name, self.content[:50]))
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = [ "name", 'email', 'website', 'content']
views.py
class PostDetailView(DetailView):
model = Post
def get_context_data(self, **kwargs):
context = super(PostDetailView, self).get_context_data(**kwargs)
context['form'] = CommentForm()
return context
class PostCommentView(SingleObjectMixin, FormView):
template_name = 'blog/post_detail.html'
form_class = CommentForm
model = Post
def post(self, request, *args, **kwargs):
self.object = self.get_object()
return super(PostCommentView, self).post(request, *args, **kwargs)
def get_success_url(self):
return reverse('post_detail', kwargs={'slug': self.object.slug})
class PostDetail(View):
def get(self, request, *args, **kwargs):
view = PostDetailView.as_view()
return view(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
view = PostCommentView.as_view()
return view(request, *args, **kwargs)
comment_form.html
<div id="respond">
<h2 class="respond-title">Leave a comment</h2>
<span class="form-caution">Make sure you enter the (*) required information where indicated. HTML code is not allowed.</span>
<form action="" method="post">
{{ form.non_field_errors }}
{% csrf_token %}
{{ form }}
<input name="submit" type="submit" id="submit" class="btn btn-primary" value="Submit Comment">
</form>
</div>
答案 0 :(得分:4)
修改的预订树遍历不是构建嵌套注释的最佳解决方案。考虑到每个新节点都必须重建整个树。例如,让我们想象一下帖子F下的评论:
// F
// / | \
// B X G
// / \
// Z Y
请注意,注释X的值为8,右值为9.但是,对于B或X的每个新子注释,这些值都将更改。例如。评论中的新评论X的X值将变为lft = 10和rht = 11.这可能导致可怕的性能,并且,正如我想象的那样,在信使的情况下丢失数据意味着信息仅发送一次(例如Django)信道)。
This post通过连接内置评论应用程序和mptt来提供实现嵌套表达系统的解决方案。它是一个旧帖子,django.contrib.comments
自Django 1.6以来已被分隔为separate project。最近Tim Graham添加了支持Django 2.0的更改,因此它似乎是最新的。
我们的想法是创建一个自定义模型和表单,它将添加到Django_comments的标题字段中。该帖子建议将其连接起来:
<强> Models.py 强>
from django_comments.models import Comment
from mptt.models import MPTTModel, TreeForeignKey
class MPTTComment(MPTTModel, Comment):
""" Threaded comments - Add support for the parent comment store and MPTT traversal"""
# a link to comment that is being replied, if one exists
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
class MPTTMeta:
# comments on one level will be ordered by date of creation
order_insertion_by=['submit_date']
class Meta:
ordering=['tree_id','lft']
<强> Forms.py 强>
from django import forms
from django.forms.widgets import widgets
from django_comments.forms import CommentForm
from models import MPTTComment
class MPTTCommentForm(CommentForm):
parent = forms.ModelChoiceField(queryset=MPTTComment.objects.all(),
required=False, widget=forms.HiddenInput)
def get_comment_model(self):
# Use our custom comment model instead of the built-in one.
return MPTTComment
def get_comment_create_data(self):
# Use the data of the superclass, and add in the parent field field
data = super(MPTTCommentForm, self).get_comment_create_data()
data['parent'] = self.cleaned_data['parent']
return data
您的应用目录中__ init__.py
from models import MPTTComment
from forms import MPTTCommentForm
def get_model():
return MPTTComment
def get_form():
return MPTTCommentForm
还有另一个django包,这个包含已嵌入的嵌套注释:django-threadedcomments。值得一试。