Python Django答题应用无法获取用户所选答案的View处理问题排查
代码问题排查与修复方案
现存核心问题点
- 表单提交路由配置错误:作答表单的action直接指向results视图,提交时根本不会触发answer视图里的POST处理逻辑,无法获取、校验用户选中的选项。
- 模板上下文变量缺失:results视图的渲染逻辑没有向模板传递「用户所选选项」的对象,模板里写的
{{ choice.selected_answer }}既无对应上下文来源,位置也不在choice循环作用域内,自然无法渲染。 - 模型定义错误:
- Choice模型内的
check_answer、get_answer方法使用了不存在的choices_set反向查询名(实际默认反向名为choice_set),且引用了不存在的is_answer判断字段,实际正确标识对错的是correct字段。 explain外键字段默认值设为空字符串,无法匹配外键关联的主键要求,会触发迁移报错。choice_text字段存在多余缩进,和类内其他字段层级不对齐,会触发Python语法错误。
- Choice模型内的
- 视图逻辑冗余错误:原answer视图中取出
selected_answer后执行的selected_answer.save()为无意义操作,没有对对象做任何修改,仅触发无意义的数据库写入。
分步修复操作
1. 修正表单提交地址
将作答表单的提交目标指向处理POST逻辑的answer视图,确保提交请求能走到选项校验流程:
<form action="{% url 'answer' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}"><p>{{ choice.choice_text }}</p></label><br> {% endfor %} <input type="submit" value="Submit Answer"> </form>
补充检查:确认项目urls.py中已为answer视图注册路由,路由name与模板中使用的'answer'保持一致,能正确反向解析出提交地址。
2. 调整视图逻辑,传递选中答案到结果页
利用session存储用户选中的选项id,解决重定向(GET请求)后上下文丢失的问题:
def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Sorry, Question does not exist") return render(request, 'index/details.html', {'question': question}) def answer(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice_id = request.POST['choice'] selected_answer = question.choice_set.get(pk=selected_choice_id) except (KeyError, Choice.DoesNotExist): return render(request, 'index/details.html', { 'question': question, 'error_message': "Please make a Valid Selection.", }) # 将选中的选项id存入session,供结果页读取 request.session['selected_choice_id'] = int(selected_choice_id) return HttpResponseRedirect(reverse('results', args=(question.id,))) def result(request, question_id): question = get_object_or_404(Question, pk=question_id) selected_choice_id = request.session.get('selected_choice_id') selected_answer = None if selected_choice_id: selected_answer = question.choice_set.filter(pk=selected_choice_id).first() # 将选中的答案对象传入模板渲染上下文 return render(request, 'index/results.html', { 'question': question, 'selected_answer': selected_answer })
3. 修正results.html渲染逻辑
移除模板中无上下文来源的{{ choice.selected_answer }}变量,替换为视图传入的selected_answer对象:
<h1>Passage / Equation:</h1> <p>{{ question.passage }}</p> </div> <div class="column" style="background-color:#bbb;"> <h1>Answer for Question: </h1> <h1>{{ question.questions_text }}</h1> {% if selected_answer %} <p>Your Choice was: <strong>{{ selected_answer.choice_text }}</strong></p> <p>Judgement: <strong>{{ selected_answer.correct }}</strong></p> {% endif %} <ul> {% for choice in question.choice_set.all %} <br> <li>► {{ choice.choice_text }}</li> <li>▬ This answer was: <b>{{ choice.correct }}</b></li> <li>◍ Explanation: {{ choice.explain }}</li> {% endfor %} </ul>
4. 修正模型定义错误
调整错误的字段、方法逻辑,确保模型可正常迁移和调用:
class Choice(models.Model): correct_choices = ( ("Correct", "Correct"), ("Incorrect", "Incorrect"), ) question = models.ForeignKey(Question, on_delete=models.CASCADE) # 修复外键无效默认值,允许空关联 explain = models.ForeignKey(Explanation, on_delete=models.CASCADE, null=True, blank=True) # 修复缩进错误 choice_text = models.CharField(max_length=200) correct = models.CharField(max_length=10, choices=correct_choices, default='Incorrect') answer = models.CharField(max_length=500, default='', blank=True) def __str__(self): return self.choice_text def check_answer(self): # 修复反向查询名和判断字段 return self.choice_set.filter(correct="Correct").exists() def get_correct_answer(self): return self.choice_set.filter(correct="Correct")
内容的提问来源于stack exchange,提问作者RemeoLong
相关产品推荐
相关产品推荐

