[Django]-Django checkbox not being submitted when unchecked

4👍

This is not about django but about html in general. This is your template:

<div class="form-group">
    <div class="checkbox">
        <label><input type="checkbox" name="{{ form.primal.name }}" value="True" id="primal1">Primal</label>
    </div>
</div>

Your checkbox, when unchecked, will not fly because it will not make a {{ form.primal.name }}=True in the url or post body.

To solve your problem, you should ensure a way to add {{ form.primal.name }}=False to the url. The standard solution involves a fixed additional field (a hidden one) like this:

<div class="form-group">
    <div class="checkbox">
        <input type="hidden" name="{{ form.primal.name }}" value="False" />
        <label><input type="checkbox" name="{{ form.primal.name }}" value="True" id="primal1">Primal</label>
    </div>
</div>

Which will generate a query string part like {{ form.primal.name }}=False if checkbox is unchecked, or {{ form.primal.name }}=False&{{ form.primal.name }}=True if checkbox is checked. In this case, only the latter occurrence counts, so you will have "True" when checked and "False" when unchecked.

Leave a comment