Django实现文章评论功能提交后表单重复提交问题求解
问题原因
你遇到的重复提交问题是因为没有遵循Post/Redirect/Get(PRG) web开发最佳实践:当前你在post方法处理完表单提交逻辑后,直接返回了渲染后的页面,浏览器此时会记录当前请求为POST类型,用户刷新页面时会自动重新提交之前的表单数据,导致重复生成评论。
修复方案
修改post方法逻辑,评论保存成功后执行重定向操作,触发GET请求拉取最新的文章详情页数据,即可避免重复提交问题,同时还可以顺便修正变量名歧义的小问题:
- 先导入Django重定向方法
from django.shortcuts import redirect
- 修改后的
PostDetailView代码:
class PostDetailView(DetailView): def get(self, request, slug, *args, **kwargs): post = Post.objects.get(slug=slug) form = CommentForm() comments = Comment.objects.filter(post=post).order_by('-date_created') context = { 'post':post, 'form': form, 'comments': comments } return render(request, 'my_news/post_detail.html', context ) def post(self, request, slug, *args, **kwargs): post = Post.objects.get(slug=slug) form = CommentForm(request.POST) if form.is_valid(): # 原变量名new_post存在歧义,修改为new_comment避免和文章对象混淆 new_comment = form.save(commit=False) new_comment.name = request.user new_comment.post= post new_comment.save() # 保存成功后重定向到当前文章详情页,post_detail替换为你实际配置的路由名称 return redirect('post_detail', slug=slug) # 不确定路由名称也可以直接用return redirect(request.path) # 表单验证失败时才返回原有上下文渲染页面展示错误 comments = Comment.objects.filter(post=post).order_by('-date_created') context = { 'post':post, 'form': form, 'comments':comments } return render(request, 'my_news/post_detail.html', context )
内容的提问来源于stack exchange,提问作者Othniel Lafond
相关产品推荐
相关产品推荐

