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/forms.py

32 lines
1.7 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.

# 赵瑞萍:评论表单模块,用于构建用户提交评论的表单,支持顶级评论和嵌套回复功能
# 基于Comment模型快速生成表单控制前端输入字段适配评论提交的数据收集需求
# 赵瑞萍导入Django表单核心模块提供表单基础构建能力
from django import forms
from django.forms import ModelForm # 导入模型表单类,实现表单与数据模型的快速绑定
from .models import Comment # 导入当前应用的Comment模型作为表单的数据源
class CommentForm(ModelForm):
"""
赵瑞萍评论提交表单类继承ModelForm实现与Comment模型的关联
扩展父评论ID字段以支持回复功能仅暴露核心输入项简化用户操作
"""
# 赵瑞萍定义父评论ID字段用于识别当前评论的回复目标实现嵌套回复
parent_comment_id = forms.IntegerField(
widget=forms.HiddenInput, # 使用隐藏输入组件,不在前端页面展示,仅用于后端传递数据
required=False # 设为非必填,顶级评论(直接评论文章)无需传入该字段
)
# 赵瑞萍:表单元数据配置类,定义模型关联、字段筛选等关键配置
class Meta:
model = Comment # 绑定Comment模型表单数据将直接映射到模型对应的字段
fields = ['body'] # 仅指定评论正文字段为前端输入项,其他字段(如作者、时间)由后端处理
def clean_body(self):
body = self.cleaned_data.get('body').strip()
if not body:
raise forms.ValidationError("评论内容不能为空")
if len(body) > 300:
raise forms.ValidationError("评论内容不能超过300个字符")
return body