Django教程中'votes'反向解析参数缺失错误求助
问题分析与修复方案
核心问题
初始参数缺失错误:
Reverse for 'votes' with arguments '('',)' not found
你使用的DetailsView(Django通用视图)会向模板传递单个Questions实例,而非列表。默认情况下,这个实例的上下文变量名是questions(模型类名小写)或object,但你最初直接在模板中使用question变量,导致找不到该变量,生成URL时传递了空参数。添加for循环后选项不显示
你添加的{% for question in latest_question_list %}依赖latest_question_list变量,但这个变量是IndexView特有的上下文,DetailsView中并不存在,因此循环不会执行,选项自然无法显示。
修复步骤
1. 优化DetailsView的上下文变量名(可选但推荐)
修改views.py中的DetailsView,明确指定上下文变量名为question,让模板代码更直观:
class DetailsView(generic.DetailView): model = Questions template_name = "polls/details.html" context_object_name = "question" # 新增这一行
2. 修正details.html模板
移除多余的for循环,直接使用DetailsView传递的单个question实例:
<h1>{{ question.question_text }}</h1> <form action="{% url 'polls:votes' question.id %}" method="post"> {% csrf_token %} <fieldset> <legend><h1>{{ question.question_text }}</h1></legend> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} </fieldset> <input type="submit" value="Vote"> </form>
验证
- 访问如
polls/1/的详情页时,模板会正确获取对应Questions实例,生成polls/1/votes/的提交URL,不再出现参数缺失错误。 question.choice_set.all会正常加载该问题下的所有选项,页面能正确显示投票选项。
内容的提问来源于stack exchange,提问作者SimpleIdeaEnjoyer
相关产品推荐
相关产品推荐

