|
|
"""评论提交及管理视图"""
|
|
|
# Create your views here.
|
|
|
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 # 评论表单
|
|
|
|
|
|
|
|
|
class CommentPostView(FormView):
|
|
|
"""评论提交视图"""
|
|
|
form_class = CommentForm
|
|
|
template_name = 'blog/article_detail.html' # 评论表单所在模板
|
|
|
|
|
|
@method_decorator(csrf_protect) # 启用CSRF保护
|
|
|
def dispatch(self, *args, **kwargs):
|
|
|
return super(CommentPostView, self).dispatch(*args, **kwargs)
|
|
|
|
|
|
def get(self, request, *args, **kwargs):
|
|
|
"""GET请求:跳转至文章详情页的评论区"""
|
|
|
article_id = self.kwargs['article_id']
|
|
|
article = get_object_or_404(Article, pk=article_id)
|
|
|
url = article.get_absolute_url()
|
|
|
return HttpResponseRedirect(url + "#comments")
|
|
|
|
|
|
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
|
|
|
})
|
|
|
|
|
|
def form_valid(self, form):
|
|
|
"""提交的数据验证合法后的逻辑"""
|
|
|
user = self.request.user
|
|
|
author = BlogUser.objects.get(pk=user.pk)
|
|
|
article_id = self.kwargs['article_id']
|
|
|
article = get_object_or_404(Article, pk=article_id)
|
|
|
|
|
|
# 检查文章是否允许评论
|
|
|
if article.comment_status == 'c' or article.status == 'c':
|
|
|
raise ValidationError("该文章评论已关闭.")
|
|
|
# 创建评论对象(暂不保存)
|
|
|
comment = form.save(False)
|
|
|
comment.article = article # 关联文章
|
|
|
from djangoblog.utils import get_blog_setting
|
|
|
# 根据博客配置决定评论是否需要审核
|
|
|
settings = get_blog_setting()
|
|
|
if not settings.comment_need_review:
|
|
|
comment.is_enable = True
|
|
|
comment.author = author
|
|
|
|
|
|
if form.cleaned_data['parent_comment_id']:
|
|
|
parent_comment = Comment.objects.get(
|
|
|
pk=form.cleaned_data['parent_comment_id'])
|
|
|
comment.parent_comment = parent_comment
|
|
|
|
|
|
comment.save(True) # 保存评论到数据库
|
|
|
# 跳转至文章页的当前评论位置
|
|
|
return HttpResponseRedirect(
|
|
|
"%s#div-comment-%d" %
|
|
|
(article.get_absolute_url(), comment.pk))
|