This is my form:
<form action="" method="POST"> {% csrf_token %}
<div class="col-4"> <input type="text" name="ad" placeholder="İsim">
{% for question in model.get_questions %}
<div class="question col-6">
<div class="header"> {{ question }} <input type="checkbox" name="answ{{forloop.counter0}}">
</div>
</div>
{% endfor %}
<input type="submit" value="Gönder">
</form>
When I try to get request.POST['ad'] in the views its pretty working but when I try to get like answ0 it doesnt working. That doesn’t appear when I print request.POST also. This is the error I receive:
MultiValueDictKeyError at /form/1
'answ0'
What is the issue?
>Solution :
If a checkbox is not checked, it is simply not part of the request. So if you tick answ2, and answ4, then answ0, answ1 and answ3 will not be part of the request.
You thus will look at:
if 'answ0' in request.POST:
pass # 🖘 checked
else:
pass # 🖘 not checked
Checkboxes are a bit tricky, just like date input for example. Therfore typically a Django Form [Django-doc] is typically used at least to validate and clean the input.