我正在尝试创建一个回复功能,该功能将允许用户回复评论,但无法将回复显示为子元素。发布后,将其显示为常规评论。
在这里是models.py以供评论
class CommentManager(models.Manager):
def all(self):
qs = super(CommentManager,self).filter(parent = None)
return qs
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name = "comments")
name = models.CharField(max_length = 200)
body = models.TextField(default = True)
pub_date = models.DateTimeField(auto_now_add = True)
parent = models.ForeignKey('self',null = True,blank = True)
class Meta:
ordering = ['-pub_date']
def __str__(self):
return self.name
def replies(self):
return Comment.objects.filter(parent = self)
@property
def is_parent(self):
if self.parent is not None:
return False
return True
这是评论的views.py
def BlogDetail(request,pk):
post = get_object_or_404(Post,pk = pk)
comment = CommentForm(request.POST or None)
subscribe = Subscribe()
parent_obj = None
if request.method == 'POST':
subscribe = Subscribe(request.POST)
comment = CommentForm(request.POST)
if comment.is_valid():
comment.instance.post = post
comment.save()
try:
parent_id = int(request.POST.get('parent_id'))
except:
parent_id = None
if parent_id:
parent_qs = Comment.objects.filter(id = parent_id)
if parent_qs.exists():
parent_obj = parent_qs.first()
elif subscribe.is_valid():
subscribe = subscribe.save(commit = True)
return render(request,'app/blog.html',{'blog_object':post,'comment':comment,
'subscribe':subscribe,'parent':parent_obj
})
在这里是用于评论和答复的html
{% for i in blog_object.get_comments %}
<div class="container">
<div class="row">
<div class="col comment_head">
<strong>{{i.name}}</strong>
<div class="col comment_body">
<p>{{i.body}}</p>
</div>
</div>
</div>
<div class="border"></div>
<form action="." method="POST">
{% csrf_token %}
<div class="col">
<div class="form-group form-group-with-icon">
{{comment}}
<div class="form-control-border"></div>
</div>
</div>
<div class="col">
<p class="form-submit">
<input type="hidden" name="parent_id" id="parent_id" value="{{i.id}}">
<input name="submit" type="submit" value="Reply Comment">
</p>
</div>
</form>
</div>
</div>
{% for u in i.replies.all %}
<div class="container">
<div class="row">
<div class="col comment_head">
<strong>{{u.name}}</strong>
<div class="col comment_body">
<p>{{u.body}}</p>
</div>
</div>
</div>
<div class="border"></div>
{% endfor %}
{% endfor %}