Django博客详情页实现自定义访客评论表单报post未定义错误
问题定位与修复方案
核心报错与功能失效原因
- 触发
name 'post' is not defined的直接原因:视图代码中创建评论时引用了不存在的变量post,当前视图作用域内拿到的当前博客实例变量名是blg - 前端表单提交无法关联存储的本质原因:自定义HTML的表单字段
name属性和Django CommentForm要求的字段名不匹配,POST请求携带的参数无法被Form校验逻辑识别 - 代码冗余问题:原逻辑先手动构造Comment对象,又单独调用
comment_form.save(),存在重复写入数据库的风险
分步修复实现
1. 修正视图层逻辑
替换原有detailview的错误逻辑,用Django ModelForm的标准关联方式绑定博客对象,去掉冗余代码,修正后的完整视图代码如下:
from django.shortcuts import get_object_or_404, redirect from .models import BlogPost, Comment from .forms import CommentForm def detailview(request, id=None): blg = get_object_or_404(BlogPost, id=id) # 获取当前博客下的所有评论,按发布时间倒序 comments = Comment.objects.filter(post=blg).order_by('-id') if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): # 暂存表单实例,暂不写入数据库 comment = comment_form.save(commit=False) # 绑定当前访问的博客对象到评论实例 comment.post = blg comment.save() # 提交成功后重定向回详情页,避免浏览器刷新导致重复提交 return redirect('blog:detail', id=blg.id) else: comment_form = CommentForm() context = { 'blg': blg, 'comments': comments, 'comment_form': comment_form, } return render(request, 'blog/blogdetail.html', context)
注意:需要把
redirect里的路由名称替换成你项目中博客详情页对应的实际路由name,确保重定向地址正确。
2. 匹配前端HTML表单的字段规则
原模板中存在两类问题:一是表单字段name和Form定义不匹配,二是模板变量引用错误。按以下规则修正表单部分:
- 评论内容textarea的原
name="comment"改为name="content",匹配Form的content字段 - 姓名输入框的原
name="author"改为name="name",匹配Form的name字段 - 邮箱输入框的
name="email"和Form要求一致,无需修改 - 删除原模板里无效的
{{comment.xxx}}变量引用,替换为从comment_form中取已填值的逻辑,避免校验失败时用户输入被清空
修正后的表单核心代码如下:
<form class="clearfix" action="" method="post" id="commentform"> {% csrf_token %} <p class="comment-notes"> <span id="email-notes">Your email address will not be published.</span> Required fields are marked <span class="required">*</span> </p> <div class="form-group"> <div class="col-sm-12"> <label>Comment<span class="required">*</span></label> <textarea name="content" cols="58" rows="7" tabindex="4" class="form-control" required> {{ comment_form.content.value|default:'' }} </textarea> </div> </div> <div class="form-group"> <div class="col-sm-6"> <label>Name<span class="required">*</span></label> <input name="name" id="author" value="{{ comment_form.name.value|default:'' }}" size="22" tabindex="1" class="form-control" type="text" required> </div> <div class="col-sm-6"> <label>Email<span class="required">*</span></label> <input name="email" id="email" value="{{ comment_form.email.value|default:'' }}" size="22" tabindex="2" class="form-control" type="text" required> </div> </div> <div class="form-group"> <div class="col-sm-12"> <button name="submit" type="submit" id="submit-button" tabindex="5" value="Submit" class="btn btn-shutter-out-horizontal btn-lg">Submit Comment</button> </div> </div> <!-- 渲染Form校验错误提示 --> {{ comment_form.errors }} </form>
说明:表单
action值设为空字符串,代表提交到当前页面的路由,无需写死接口地址。
3. 可选优化:增强表单校验能力
现有forms.py已经可以实现基础功能,如需自动校验邮箱格式、统一表单样式,可在CommentForm中补充widget配置:
from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('content', 'email', 'name',) widgets = { 'email': forms.EmailInput(attrs={'class': 'form-control'}), 'name': forms.TextInput(attrs={'class': 'form-control'}), 'content': forms.Textarea(attrs={'class': 'form-control', 'rows': 7}), }
内容的提问来源于stack exchange,提问作者Sandeep Gupta
相关产品推荐
相关产品推荐

