You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DjangoBlog/comments/views.py

38 lines
1.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# comments/views.py
# DZQ: 评论模块的视图函数文件处理评论相关的HTTP请求
from django.shortcuts import get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Comment
from .forms import CommentForm
from blog.models import Post
# DZQ: 添加评论视图函数 - 处理用户提交评论的请求
@login_required # DZQ: 登录要求装饰器,确保只有登录用户才能发表评论
def add_comment(request, post_id):
"""添加评论"""
# DZQ: 获取指定ID且状态为已发布的文章如果不存在则返回404错误
post = get_object_or_404(Post, id=post_id, status='published')
# DZQ: 只处理POST请求GET请求直接重定向
if request.method == 'POST':
# DZQ: 实例化评论表单传入POST数据
form = CommentForm(request.POST)
# DZQ: 表单验证通过的处理逻辑
if form.is_valid():
# DZQ: commit=False表示先不保存到数据库允许设置额外字段
comment = form.save(commit=False)
comment.post = post # DZQ: 设置评论关联的文章
comment.author = request.user # DZQ: 设置评论作者为当前登录用户
comment.save() # DZQ: 将评论保存到数据库
# DZQ: 添加成功消息,将在下次请求时显示给用户
messages.success(request, '评论发表成功!')
else:
# DZQ: 表单验证失败,添加错误消息
messages.error(request, '评论发表失败,请检查输入内容。')
# DZQ: 重定向回文章详情页面,无论评论成功与否都返回文章页面
return redirect('detail', post_id=post_id)