首页 > 解决方案 > request.POST 上的 django 单选按钮不起作用

问题描述

我正在尝试使用以下形式从 radio.input 中读取值

def question_detail(request,question_id,quiz_id):
q = Quiz.objects.get(pk = quiz_id)
que = Question.objects.get(pk = question_id)
count = q.question_set.count()
try:
    selected_choice = que.answer_set.get(pk=request.POST['choice'])
except(KeyError, Answer.DoesNotExist):
    come = que.rank
    came = come + 1
    later_question = q.question_set.get(rank=came)
    return render(request, 'app/question_detail.html',{'que': que, 'count': count, 'later_question': later_question})
else:
    if selected_choice.correct is True:
        try:
            come = que.rank
            came = come + 1
            later_question = q.question_set.get(rank=came)
        except:
            come = que.rank
            came = come
            later_question = q.question_set.get(rank=came)
    else:
        come = que.rank
        later_question = q.question_set.get(rank=come)
    return render(request, 'app/question_detail.html',{'count': count, 'que': que, 'later_question': later_question})

但是当我尝试访问网页时,它会抛出一个 Keyerror,请帮助

<form action="{% url 'app:detail' quiz_id=que.quiz.id question_id=later_question.id%}" method="post">{% csrf_token%}
{% for choice in que.answer_set.all %}
    <input type="radio" name='choice' value="{{choice.id}}">
    <label>{{choice.answer}}-{{choice.correct}}-{{choice.rank}}</label><br>
{% endfor %}

标签: djangodjango-rest-frameworkdjango-formsdjango-viewsradio-button

解决方案


推荐阅读