Search code examples
djangodatatablesdjango-templatesdjango-2.1

Django/DataTables - Template Loop breaks DataTable


When placing a template loop in my table-row my DataTable breaks.

<table id="store_table" class="table-striped table-hover">
  <thead class="thead-light">
    <tr>
      <th>Store #</th>
      <th>Name</th>
      <th>Phone</th>
      <th>City</th>
      <th>State</th>
    </tr>
  </thead>

    <tbody>
    {% for store in stores %}
        <tr id="table-row">
            <td><a href="/stores/{{ store.pk }}">{{ store.store_number }}</a></td>
            <td><a href="/stores/{{ store.pk }}">{{ store.name }}</a></td>
            <td>{{ store.phone }}</td>
            <td>{{ store.city }}</td>
            <td>{{ store.state }}</td>
            {% for circuit in store.circuit_set.all %}
                <td>{{ circuit.circuit_id }}</td>
            {% endfor %}
           <td>{{ store.postal }}</td>

        </tr>
    {% endfor %}
    </tbody>
    </table>

Console Output:

jQuery.Deferred exception: i is undefined Ha@http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js:24:397
O@http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js:16:421
na/<@http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js:17:21
map/<@https://code.jquery.com/jquery-3.3.1.min.js:2:1324
map@https://code.jquery.com/jquery-3.3.1.min.js:2:3169
map@https://code.jquery.com/jquery-3.3.1.min.js:2:1292
na@http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js:16:497
e@http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js:92:431
n/<@http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js:93:118
each@https://code.jquery.com/jquery-3.3.1.min.js:2:2571
each@https://code.jquery.com/jquery-3.3.1.min.js:2:1238
n@http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js:83:194
h.fn.DataTable@http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js:165:488
@http://10.200.20.63:8080/stores/:12810:19
l@https://code.jquery.com/jquery-3.3.1.min.js:2:29373
a/</c<@https://code.jquery.com/jquery-3.3.1.min.js:2:29677
 undefined

So I'm assuming this is because {% %} isn't a recognized/handleable table element.


Solution

  • You table break for this

    {% for circuit in store.circuit_set.all %}
        <td>{{ circuit.circuit_id }}</td>
    {% endfor %}
    

    If you change this to

    <td>
    {% for circuit in store.circuit_set.all %}
        <p>{{ circuit.circuit_id }}</p>
    {% endfor %}
    </td>
    

    This may works.