# zr 评论视图模块 from django.core.exceptions import ValidationError from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_protect from django.views.generic.edit import FormView from accounts.models import BlogUser from blog.models import Article from .forms import CommentForm from .models import Comment # zr 评论提交视图类 class CommentPostView(FormView): # zr 使用评论表单类 form_class = CommentForm # zr 指定模板名称 template_name = 'blog/article_detail.html' # zr 添加CSRF保护装饰器 @method_decorator(csrf_protect) def dispatch(self, *args, **kwargs): return super(CommentPostView, self).dispatch(*args, **kwargs) # zr 处理GET请求,重定向到文章详情页 def get(self, request, *args, **kwargs): article_id = self.kwargs['article_id'] article = get_object_or_404(Article, pk=article_id) url = article.get_absolute_url() return HttpResponseRedirect(url + "#comments") # zr 处理表单验证失败的情况 def form_invalid(self, form): article_id = self.kwargs['article_id'] article = get_object_or_404(Article, pk=article_id) return self.render_to_response({ 'form': form, 'article': article }) # zr 处理表单验证成功的情况 def form_valid(self, form): """提交的数据验证合法后的逻辑""" # zr 获取当前用户信息 user = self.request.user author = BlogUser.objects.get(pk=user.pk) # zr 获取文章信息 article_id = self.kwargs['article_id'] article = get_object_or_404(Article, pk=article_id) # zr 检查文章是否允许评论 if article.comment_status == 'c' or article.status == 'c': raise ValidationError("该文章评论已关闭.") # zr 创建评论对象但不立即保存到数据库 comment = form.save(False) comment.article = article # zr 获取博客设置,判断评论是否需要审核 from djangoblog.utils import get_blog_setting settings = get_blog_setting() if not settings.comment_need_review: comment.is_enable = True comment.author = author # zr 处理回复评论的情况 if form.cleaned_data['parent_comment_id']: parent_comment = Comment.objects.get( pk=form.cleaned_data['parent_comment_id']) comment.parent_comment = parent_comment # zr 保存评论到数据库 comment.save(True) # zr 重定向到文章页面并定位到新评论 return HttpResponseRedirect( "%s#div-comment-%d" % (article.get_absolute_url(), comment.pk))