You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django实现文章评论功能提交后表单重复提交问题求解

问题原因

你遇到的重复提交问题是因为没有遵循Post/Redirect/Get(PRG) web开发最佳实践:当前你在post方法处理完表单提交逻辑后,直接返回了渲染后的页面,浏览器此时会记录当前请求为POST类型,用户刷新页面时会自动重新提交之前的表单数据,导致重复生成评论。

修复方案

修改post方法逻辑,评论保存成功后执行重定向操作,触发GET请求拉取最新的文章详情页数据,即可避免重复提交问题,同时还可以顺便修正变量名歧义的小问题:

  1. 先导入Django重定向方法
from django.shortcuts import redirect
  1. 修改后的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 21:18:02