Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MultiValueDictKeyError at generated form element

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading