当前位置: 首页 > 后端技术 > Python

Django20200424博客开发019

时间:2023-03-26 13:53:35 Python

目标效果:可以对自己写的博文进行评论,可以对评论进行回复。在comment/models.py中为类Comment添加新内容:树结构#comment/models.pyroot=models.ForeignKey('self',related_name='root_comment',null=True,on_delete=models.DO_NOTHING)#设计底层结构需要parent=models.ForeignKey('self',related_name='parent_comment',null=True,on_delete=models.DO_NOTHING)#外键指向自身reply_to=models.ForeignKey(User,related_name="replies",null=True,on_delete=models.DO_NOTHING)#回复谁def__str__(self):#为了显示评论的具体内容而不是对象returnself.text迁移并添加新博客,评论数为0,将主键值添加到comment/admin中的amin.pylist_display=('id','content_object','text','comment_time','user')#id为主键修改博客中的commentcomments\_detailmethodinblog/views.py=Comment.objects.filter(content_type=blog_content_type,object_id=blog.pk,parent=None)#添加parent=None来增加ase初始化值在blog_detail.html上面没有添加评论:回复{%forreplyincomment.root_comment.all%}{{reply.user.username}}({{reply.comment_time|date:"Y-m-dH:i:s"}})回复{{reply.reply_to.username}}:{{reply.text|safe}}

href=Reply
{%endfor%}回到admin,设置评论回复评论回复添加样式:blog.css:div.comment{border-bottom:1pxdashed#ccc;底部边距:0.5em;padding-bottom:0.5em;}div.reply{margin-left:2em;}在comment/forms.py中添加reply_comment_id字段:reply_comment_id=forms.IntegerField(widget=forms.HiddenInput(attrs={'id':'reply_comment_id'}))效果如下:在log_detail.html中添加函数提交按钮:varhtml=$("#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();});}然后在欢迎评论下方添加:

Reply:

在comment/forms.py中添加clean_reply_comment_id方法来回复内容进行验证;来自.models导入评论..defclean_reply_comment_id(self):reploy_comment_id=self.cleaned_data['reque__comment_id']如果reque_comment_id<0:提高forms.validationError(validationerror(']=NoneelifComment.objects.filter(pk=reply_comment_id).exists():self.cleaned_data['parent']=Comment.objects.get(pk=reply_comment_id)else:raiseforms.ValidationError('replyerror')returnreply_comment_id然后在comment/views.py中加入判断parent=comment_form.cleaned_data['parent']ifnotparentisNone:comment.root=parent.rootifnotparent.rootisNoneelseparentcomment.parent=parentcomment.reply_to=parent.usercomment.save()...data['text']=comment.textifnotparentisNone:data['reply_to']=comment.reply_to.usernameelse:data['reply_to']=''data['pk']=comment.pkdata['root_pk']=comment.root.pkifnotcomment.rootisNoneelse''效果图:修改blog/views.py中的内容,让评论保持正序,回复可以逆序。context['comments']=comments.order_by('-comment_time')效果: