Search code examples
javascripthtmldjangohtml-table

How to populate checkboxes in a table with values from a Django model


My html table has a column that contains a checkbox. The user can check or uncheck it. The value (boolean) is stored in the Django model Subscriber under Subscriber.participates. All objects of Subscriber are imported into the HTML using a Django view (context = {'subscribers' : Subscriber.objects.all(),}).

When loading the table, the checkboxes must be set to the correct value. To that purpose I have written a javascript function, which is invoked in the <input> element. However, the checkboxes all remain unchecked, though I have verified through /admin/ in Django that some of the values in the dbase are indeed "TRUE". firstName and lastName load without any problem into the table. What did I do wrong?

<head>
    <meta charset="UTF-8">
    <title>Participants</title>
    <script>
    function checkBox() {
        if({{ x.participates }}){
              document.getElementById("checkbox").checked = true;
        } else {
              document.getElementById("checkbox").checked = false;
        }
    }
    </script>
</head>
<body>
  <table>
  {% for x in subcribers %}
      <tr>
          <form action="updateSuscribers/{{ x.id }}" method="post">
              {% csrf_token %}                
              <td>{{ x.firstName }}</td>
              <td>{{ x.lastName }}</td>
              <td>
                  <input id="checkbox" type="checkbox" name="participates" onload="checkBox()">
              </td>           
          </form>
      </tr>
  {% endfor %}
  </table>
</body>

Solution

  • you don't need a js function to render existing data with the Checked/Unchecked Box.

    assuming boolean field name is_subscribed

    {% for sub in subscribers %}
       {% if sub.is_subscribed %}
         <input type="checkbox" checked>
       {% else %}
         <input type="checkbox">
       {% endif %}
    {% endfor %}
    

    but Yes you gonna need js click event if you want it to update using the Click on Realtime without Refreshing page