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

Django detail.html出现NoReverseMatch错误求助

解决Django中Reverse for 'vote'找不到的报错问题

嘿,这个问题我太熟了!你遇到的报错Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls\/(?P<question_id>[0-9]+)\/$'],核心原因就是URL反转时需要的question_id参数是空值,而index.html能正常运行,刚好帮我们锁定了问题的关键。

问题根源拆解

你已经精准发现views.py的bug了——模板需要接收Question对象,但你实际传递给detail模板的只有choice_set(因为Question是Choice的外键)。这就导致detail模板里根本拿不到有效的Question实例,自然没法生成正确的question.id参数传给voteURL。

比如index.html里你用{% url 'vote' question.id %}能正常运行,是因为这里的question是实打实的Question对象,能提供有效的id;但detail.html里,因为视图没传Question对象,你可能误把choice相关属性(甚至是空值)传进去了,才会出现参数为空的报错。

具体修复步骤

  • 第一步:修正views.py的上下文传递
    确保在渲染detail页面的视图函数里,把Question对象也传给模板,而不只是它的choice_set。比如原本错误的代码可能是这样:

    def detail(request, question_id):
        question = get_object_or_404(Question, pk=question_id)
        # 错误:只传了choice集合,没传Question对象本身
        return render(request, 'polls/detail.html', {'choices': question.choice_set.all()})
    

    改成这样:

    def detail(request, question_id):
        question = get_object_or_404(Question, pk=question_id)
        # 正确:同时传递Question对象和它的选项集合
        return render(request, 'polls/detail.html', {'question': question, 'choices': question.choice_set.all()})
    
  • 第二步:修正detail.html的URL反转代码
    在detail.html里,确保调用voteURL时传入的是Question对象的id,比如:

    <a href="{% url 'vote' question.id %}">进入投票</a>
    

    别用choice的属性(比如choice.id)或者其他空值替代,因为voteURL的规则明确要求接收Question的id作为参数。

  • 第三步:验证修复效果
    重启Django服务,访问detail页面,查看页面生成的a标签href属性,应该是类似/polls/1/这样的有效格式,而不是空参数的无效链接。

内容的提问来源于stack exchange,提问作者Henry Li

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:23:56