0

I am creating a multi-choice quiz app, I have created a view which shows the question and 4 option. I have given radio button to each option but is giving me this error:

MultiValueDictKeyError at /quiz/2/11/ 'choice'

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>
Ivan Starostin
  • 7,445
  • 5
  • 17
  • 32

1 Answers1

0

Okay like I said in my comment, you're most likely getting that error because the POST object will be empty during a normal GET request. So you should wrap everything that's meant to happen after a request in an IF block:

if request.method === 'POST':
    selected_choice = que.answer_set.get(pk=request.POST['choice'])
    # Every other post-submit task  

You should always check for the POST method in your views if you're expecting form data. Others have answered this more in-depth before so I would just direct you there:

What does request.method == "POST" mean in Django?

onyeka
  • 1,424
  • 16
  • 14
  • hey but i m following django official documentation and in which this i not given and i still dont know how should i put this in my views what shold i write in else: – Swapnil Mangaonker Apr 13 '20 at 14:04