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> 
2
  • Does this show up when you submit the form, or just when loading the page? You should always be checking if request.method is POST, it might be empty. Commented Apr 11, 2020 at 17:49
  • While loading the page Commented Apr 11, 2020 at 18:33

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

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:

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.