我正在创建一个多选择问答应用程序,我已经创建了一个视图,其中显示了问题和4选项。我已经给出了每个选项的单选按钮,但是给了我这个错误:
MultiValueDictKeyError /quiz/2/11/“选择”
views.py
def question_detail(request,question_id,quiz_id):
q = Quiz.objects.get(pk=quiz_id)
que = Question.objects.get(pk=question_id)
ans = que.answer_set.all()
selected_choice = que.answer_set.get(pk=request.POST['choice'])
if selected_choice is True:
come = que.rank
came = come + 1
later_question = q.question_set.get(rank=came)
return render(request,'app/question_detail.html',{'que':que , 'later_question':later_question, 'ans':ans})
else:
come = que.rank
later_question = q.question_set.get(rank=come)
return render(request, 'app/question_detail.html', {'que': que, 'later_question': later_question, 'ans': ans})question_detail.html
<form action="{% 'app:detail' quiz_id=quiz.id question_id=que.id %}" method="post">
{% csrf_token %}
{% for choice in que.answer_set.all %}
<input type="radio" name="choice" id="choice{{forloop.counter}}" value="{{choice.id}}">
<label for="choice{{forloop.counter}}">{{choice.answer}}</label>
{% endfor %}
</form>发布于 2020-04-11 19:54:03
好的,就像我在评论中说的,您很可能会收到这个错误,因为在正常的POST请求期间,GET对象将是空的。因此,您应该将在请求之后发生的所有内容包装在IF块中:
if request.method === 'POST':
selected_choice = que.answer_set.get(pk=request.POST['choice'])
# Every other post-submit task 如果需要表单数据,应该始终在视图中检查POST方法。其他人也曾对此作过更深入的回答,所以我会直接告诉你们:
https://stackoverflow.com/questions/61159751
复制相似问题