When I am submitting the form, the question id’s that are inside the view do not match with the question id’s from the request.POST.
When submitting the from, the print statements from the view below are:
<QueryDict: {‘csrfmiddlewaretoken’: [‘token here’], ‘question_15’:
[‘option1’], ‘question_17’: [‘option1’]}>question_4 question_5
Inside the request.POST the id’s are 15 and 17, and inside the view 4, 5.
Everytime i am submitting the form, the id’s do not match.
View:
@login_required
def quiz_view(request):
questions = QuizQuestion.objects.order_by('?')[:2]
user = request.user
if request.method == 'POST':
print(request.POST)
for question in questions:
input_name = f"question_{question.id}"
print(input_name)
option_selected = request.POST.get(input_name)
if option_selected:
# Check if the user has already responded to this question
existing_response = QuizUserResponse.objects.filter(user=user, question=question).first()
if existing_response:
# Update existing response
existing_response.response_text = getattr(question, option_selected)
existing_response.save()
else:
# Create new response
QuizUserResponse.objects.create(user=user, question=question, response_text=getattr(question, option_selected))
return redirect('users:gaming_quiz')
else:
context = {
"questions": questions,
}
return render(request, 'general/quiz_template.html', context)
HTML:
<form method="post">
{% csrf_token %}
{% for question in questions %}
<div>
<label class="question">{{ question.question_text }}</label>
<ul class="errors">
{% for error in form.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
<div>
<label class="form-check-inline">
<input type="radio" name="question_{{ question.id }}" value="option1"> {{ question.option1 }}
</label>
<label class="form-check-inline">
<input type="radio" name="question_{{ question.id }}" value="option2"> {{ question.option2 }}
</label>
<label class="form-check-inline">
<input type="radio" name="question_{{ question.id }}" value="option3"> {{ question.option3 }}
</label>
<label class="form-check-inline">
<input type="radio" name="question_{{ question.id }}" value="option4"> {{ question.option4 }}
</label>
</div>
</div>
{% endfor %}
<button type="submit">Submit</button>
</form>