没有过开发经验的新手,拜托各位大神指点一下,我应该怎么改进下面我下面这种二级评论的设计?如果描述的不够详细,我再补充。
ps: 我的思路,就是一篇文章和一级评论形成一对多的关系,然后一级评论和二级评论又形成一对多的关系。
models.py
class BlogComment(models.Model):
"""这是一级评论"""
user_name = models.CharField('Name', max_length=100) # 指定用户名
body = models.TextField('Content') # 评论的主体
# 将一级评论关联对应的文章
article = models.ForeignKey('Article', verbose_name='Article',
on_delete=models.CASCADE)
class SubComment(BlogComment):
"""这是二级评论,继承自一级评论,但是增加了一个parent_comment属性"""
# 将二级评论关联对应的一级评论
parent_comment = models.ForeignKey('BlogComment', verbose_name='BlogComment',
on_delete=models.CASCADE)
froms.py中指定评论的表单
class BlogCommentForm(forms.ModelForm):
"""一级评论的表单"""
class Meta:
model = BlogComment # 指定一级评论的model
fields = ['user_name', 'body']
widgets = {
'user_name': forms.TextInput(attrs={
'required': 'required',
}),
'body': forms.Textarea(attrs={
'required': 'required',
}),
}
class SubCommentForm(BlogCommentForm):
"""二级评论的表单,继承自一级评论的表单"""
class Meta:
model = SubComment # 制定二级评论的model
fields = copy.deepcopy(BlogCommentForm.Meta.fields)
widgets = copy.deepcopy(BlogCommentForm.Meta.widgets)
views.py
class CommentPostView(FormView):
"""一级评论视图层"""
form_class = BlogCommentForm
template_name = 'blog/article.html'
def form_valid(self, form):
# 保存表单到数据库
comment = form.save(commit=False)
comment.save()
return HttpResponseRedirect('/')
def form_invalid(self, form):
# ... 一些提示用户表单输入不合理的信息
class SubCommentView(CommentPostView):
"""二级评论视图层,继承与一级评论视图层"""
# 覆盖form_class成二级评论的表单
form_class = SubCommentForm
梦里花落0921
相关分类