0

This is my first Django project I have this simple form which I would like to submit all row values (checked or unchecked), The error I am facing is that it only sends row{num} value if it is checked.

<script>
function calc(elemId)
{
  var elem = document.getElementsByName(elemId)[0];
  if (elem.checked)
  {
      elem.value = 1;
  } else {
      elem.value = 0;
  }
}
</script>
<div class="container pt-3">
    <form action="." method="post">
        <table class="table table-hover">
        <thead>
            <tr>
                <th scope="col">#</th>
                <th scope="col">Keyword</th>
                 <th scope="col">seller_items</th>
                <th scope="col">Total</th>
                <th scope="col">checked</th>
            </tr>
        </thead>
                {% csrf_token %}
                {{ form|crispy }}
            {%for i in data%}
                <tr >
                    <th scope="row">{{forloop.counter}}</th>
                    <td>{{i.keyword}}</td>
                    <td>{{i.seller_items}}</td>
                    <td>{{i.total_found}}</td>
                    <td>
                        {% if i.checked %}
                        <input type="checkbox" name="row{{i.id}}" value="1" checked="checked" onclick="calc('row{{i.id}}')"/>
                        {%else%}
                        <input  type="checkbox" name="row{{i.id}}" value="0" onclick="calc('row{{i.id}}')"/>
                        {%endif%}
                    </td>
                </tr>
            {% endfor %}
        </table>
        <div class="row">
            <div class="col-12">
                <button class="btn btn-primary float-right" type="submit">Update</button>
            </div>
        </div>
    </form>

the form is submitted when the button is pushed but only checked boxes rows are in the post request

2 Answers2

0

That's the expected behaviour from webbrowsers. If the checkbox is not False, no data will be send. If it is True 'on' will be send.

While cleaning your form, Django will automatically set the cleaned_data value to False if it is not there and handle the data wrangling.

hendrikschneider
  • 1,696
  • 1
  • 14
  • 26
0

Check this answer: https://stackoverflow.com/a/1992745/14091199

You can put a hidden input with the same name as the checkbox that will not be checked. The hidden input is always successful and sent to the server but if the checkbox is checked it will override the hidden input.

<form>
    <input type='hidden' value='0' name='selfdestruct'>
    <input type='checkbox' value='1' name='selfdestruct'>
</form>
Hamza Ali
  • 96
  • 2
  • 4