/postcomment',
+ # 对应的视图类:使用CommentPostView类视图处理该路径的请求
views.CommentPostView.as_view(),
+ # URL名称:命名为'postcomment',用于在模板和代码中进行URL反向解析
name='postcomment'),
-]
+]
\ No newline at end of file
diff --git a/src/DjangoBlog/comments/utils.py b/src/DjangoBlog/comments/utils.py
index f01dba7..37cf9d2 100644
--- a/src/DjangoBlog/comments/utils.py
+++ b/src/DjangoBlog/comments/utils.py
@@ -1,17 +1,29 @@
+# 模块级注释:评论邮件通知模块
+# 本模块提供评论相关的邮件通知功能,包括新评论确认邮件和评论回复通知邮件
import logging
+# 导入Django国际化翻译模块
from django.utils.translation import gettext_lazy as _
+# 导入工具函数:获取当前站点信息和发送邮件
from djangoblog.utils import get_current_site
from djangoblog.utils import send_email
+# 创建日志记录器实例,用于记录邮件发送过程中的错误信息
logger = logging.getLogger(__name__)
+# 函数级注释:发送评论邮件通知
+# 主要功能:向评论作者发送评论确认邮件,如果是对回复的评论,则同时向被回复者发送通知邮件
def send_comment_email(comment):
+ # 获取当前站点域名,用于构建完整的文章链接
site = get_current_site().domain
+ # 邮件主题:使用国际化翻译
subject = _('Thanks for your comment')
+ # 构建完整的文章URL地址
article_url = f"https://{site}{comment.article.get_absolute_url()}"
+
+ # 构建评论确认邮件的HTML内容
html_content = _("""Thank you very much for your comments on this site
You can visit %(article_title)s
to review your comments,
@@ -19,10 +31,17 @@ def send_comment_email(comment):
If the link above cannot be opened, please copy this link to your browser.
%(article_url)s""") % {'article_url': article_url, 'article_title': comment.article.title}
+
+ # 获取评论作者的邮箱地址
tomail = comment.author.email
+ # 发送评论确认邮件给评论作者
send_email([tomail], subject, html_content)
+
+ # 异常处理块:处理评论回复通知邮件的发送
try:
+ # 检查是否存在父级评论(即当前评论是否为回复评论)
if comment.parent_comment:
+ # 构建回复通知邮件的HTML内容
html_content = _("""Your comment on %(article_title)s
has
received a reply.
%(comment_body)s
@@ -32,7 +51,11 @@ def send_comment_email(comment):
%(article_url)s
""") % {'article_url': article_url, 'article_title': comment.article.title,
'comment_body': comment.parent_comment.body}
+ # 获取被回复评论作者的邮箱地址
tomail = comment.parent_comment.author.email
+ # 发送回复通知邮件给被回复者
send_email([tomail], subject, html_content)
+ # 捕获邮件发送过程中可能出现的任何异常
except Exception as e:
- logger.error(e)
+ # 记录异常信息到日志,但不中断程序执行
+ logger.error(e)
\ No newline at end of file
diff --git a/src/DjangoBlog/comments/views.py b/src/DjangoBlog/comments/views.py
index ad9b2b9..87f5aad 100644
--- a/src/DjangoBlog/comments/views.py
+++ b/src/DjangoBlog/comments/views.py
@@ -1,3 +1,5 @@
+# 模块级注释:Django视图模块 - 评论系统
+# 本模块定义了评论提交的视图处理逻辑,包括评论验证、保存和重定向等功能
# Create your views here.
from django.core.exceptions import ValidationError
from django.http import HttpResponseRedirect
@@ -6,58 +8,94 @@ 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
+# 类级注释:评论提交视图类
+# 继承自FormView,处理评论表单的提交和验证
class CommentPostView(FormView):
+ # 指定使用的表单类
form_class = CommentForm
+ # 指定模板名称
template_name = 'blog/article_detail.html'
+ # 方法装饰器:添加CSRF保护
@method_decorator(csrf_protect)
def dispatch(self, *args, **kwargs):
+ # 调用父类的dispatch方法,确保CSRF保护生效
return super(CommentPostView, self).dispatch(*args, **kwargs)
+ # GET请求处理方法
def get(self, request, *args, **kwargs):
+ # 从URL参数获取文章ID
article_id = self.kwargs['article_id']
+ # 获取文章对象,如果不存在返回404
article = get_object_or_404(Article, pk=article_id)
+ # 获取文章的绝对URL
url = article.get_absolute_url()
+ # 重定向到文章详情页的评论区域
return HttpResponseRedirect(url + "#comments")
+ # 表单验证失败处理方法
def form_invalid(self, form):
+ # 获取文章ID
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
+ # 根据用户ID获取用户对象
author = BlogUser.objects.get(pk=user.pk)
+ # 从URL参数获取文章ID
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))
+ (article.get_absolute_url(), comment.pk))
\ No newline at end of file