修改comment模型,其中parent为外键,表示父亲是哪个,root也为外键,表示根是哪个,related_name反向解析,找到对应根下的全部评论或对应用户的全部评论,reply_to表示回复的对象 ,null=true表示允许为空,blank=true表示后台管理可以为空
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
# Create your models here.
class Comment(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
text = models.TextField()
comment_time = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, related_name="comments", on_delete=models.DO_NOTHING)
root = models.ForeignKey('self', related_name='root_comment', null=True,blank=True,on_delete=models.DO_NOTHING)
parent = models.ForeignKey('self', related_name='parent_comment',blank=True, null=True, on_delete=models.DO_NOTHING)
reply_to = models.ForeignKey(User, related_name="replies",blank=True, null=True, on_delete=models.DO_NOTHING)
def __str__(self):
return self.text
class Meta:
ordering = ['comment_time']
修改对应的表单
输入对应的reply_comment_id,给一个id,如果这个值为0表示初始评论
from django import forms
from django.contrib.contenttypes.models import ContentType
from ckeditor.widgets import CKEditorWidget
from django.db.models import ObjectDoesNotExist
from comments.models import Comment
class CommentForm(forms.Form):
content_type = forms.CharField(widget=forms.HiddenInput())
object_id = forms.IntegerField(widget=forms.HiddenInput())
text = forms.CharField(label=False,
widget=CKEditorWidget(config_name='comment_ckeditor'),
error_messages={'required': '评论内容不能为空'})
reply_comment_id = forms.IntegerField(widget=forms.HiddenInput(attrs={'id': 'reply_comment_id'}))
def __init__(self, *args, **kwargs):
if 'user' in kwargs:
self.user = kwargs.pop('user')
super(CommentForm, self).__init__(*args, **kwargs)
def clean(self):
if self.user.is_authenticated:
self.cleaned_data['user'] = self.user
else:
raise forms.ValidationError('用户尚未登录')
content_type = self.cleaned_data['content_type']
object_id = self.cleaned_data['object_id']
try:
model_class = ContentType.objects.get(model=content_type).model_class()
model_obj = model_class.objects.get(pk=object_id)
self.cleaned_data['content_object'] = model_obj
except Exception as e:
raise forms.ValidationError('评论对象不存在')
return self.cleaned_data
def clean_reply_comment_id(self):
reply_comment_id = self.cleaned_data['reply_comment_id']
if reply_comment_id < 0:
raise forms.ValidationError('回复出错')
elif reply_comment_id == 0:
self.cleaned_data['parent'] = None
elif Comment.objects.filter(pk=reply_comment_id).exists():
self.cleaned_data['parent'] = Comment.objects.get(pk=reply_comment_id)
else:
raise forms.ValidationError('回复出错')
return reply_comment_id
blog.detail进行修改
{% extends 'base.html' %}
{#页面标题#}
{% block title %}
{{blog.title}}
{% endblock %}
{% load static %}
{%block head_extend%}
{% endblock %}
{%block nav_blog_active%}
active
{%endblock%}
{%block content%}
{{blog.title}}
- 作者:{{blog.author}}
-
分类:
{{blog.blog_type}}
- 发表日期:{{blog.created_time|date:"Y-m-d H:i:s"}}
- 阅读:({{blog.get_read_num}})
{{blog.content|safe}}
上一篇
{%if previous_blog %}
{{previous_blog.title}}
{%else%}
没有了
{%endif%}
下一篇
{%if next_blog %}
{{next_blog.title}}
{%else%}
没有了
{%endif%}
评论列表
{% for comment in comments %}
{{ comment.user.username }}
({{ comment.comment_time|date:"Y-m-d H:i:s" }}):
{{ comment.text|safe }}
回复
{% for reply in comment.root_comment.all %}
{{ reply.user.username }}
({{ reply.comment_time|date:"Y-m-d H:i:s" }})
回复
{{ reply.reply_to.username }}:
{{ reply.text|safe }}
回复
{% endfor %}
{% empty %}
暂无评论
{% endfor %}
{% endblock %}
{%block script_extends %}
相应的方法,初始化reply_comment_id为0 ,这里修改一下排序,让评论按时间倒序
def blog_detail(request, blog_pk):
context = {}
blog = get_object_or_404(Blog, pk=blog_pk)
read_cookie_key=read_statistic_one_read(request,blog)
blog_content_type=ContentType.objects.get_for_model(blog)
comments=Comment.objects.filter(content_type=blog_content_type,object_id=blog.pk,parent=None)
context['previous_blog'] = Blog.objects.filter(created_time__gt=blog.created_time).last()
context['next_blog'] = Blog.objects.filter(created_time__lt=blog.created_time).first()
context['blog'] = blog
context['comments'] = comments.order_by('-comment_time')
data={}
data['content_type']=blog_content_type.model
data['object_id']=blog_pk
data['reply_comment_id']=0
context['comment_form']=CommentForm(initial=data)
response = render(request,'blog/blog_detail.html', context)
response.set_cookie(read_cookie_key,'true') # 关闭浏览器,cookie才无效
return response
blogdetail增加一个js方法定位到富文本编辑框,同时修改相应的表单提交的值
function reply(reply_comment_id)
{
$('#reply_comment_id').val(reply_comment_id);
var html=$("#comment_"+reply_comment_id).html();
$('#reply_content').html(html);
$('#reply_content_container').show();
$('html').animate({scrollTop: $('#comment_form').offset().top - 60}, 300, function(){
CKEDITOR.instances['id_text'].focus();
});
}
对应的提交评论方法,讨论是否有父节点
def update_comment(request):
referer = request.META.get('HTTP_REFERER', reverse('home'))
comment_form = CommentForm(request.POST, user=request.user)
data = {}
if comment_form.is_valid():
# 检查通过,保存数据
comment = Comment()
comment.user = comment_form.cleaned_data['user']
comment.text = comment_form.cleaned_data['text']
comment.content_object = comment_form.cleaned_data['content_object']
parent = comment_form.cleaned_data['parent']
if not parent is None:
comment.root = parent.root if not parent.root is None else parent
comment.parent = parent
comment.reply_to = parent.user
comment.save()
# 返回数据
data['status'] = 'SUCCESS'
data['username'] = comment.user.username
data['comment_time'] = comment.comment_time.strftime('%Y-%m-%d %H:%M:%S')
data['text'] = comment.text
if not parent is None:
data['reply_to'] = comment.reply_to.username
else:
data['reply_to'] = ''
data['pk'] = comment.pk
data['root_pk'] = comment.root.pk if not comment.root is None else ''
else:
data['status'] = 'ERROR'
data['message'] = list(comment_form.errors.values())[0][0]
return JsonResponse(data)
ajax异步处理方法,根据reply_comment_id的值来确定是否是原始评论还是回复
提交评论区域
{%if user.is_authenticated %} {%else%} 您尚未登录登录后方可评论 登录 or 注册 {%endif%}