Beginner Beginner - 4 months ago 50
Python Question

Django Datatables from model

I have a simple model in my django app that I am displaying as a table. I would like to change the table to a datatable. However even after following all the steps listed ont eh datatables.net website I cant seem to convert my table into a datatable:

models.py

from __future__ import unicode_literals

from django.db import models


class Profile(models.Model):
name = models.CharField(max_length=128)
email = models.EmailField(null=False)
city = models.CharField(null=False, max_length=128)

def __unicode__(self):
return self.name


views.py

from django.shortcuts import render
from django.http import HttpResponse
from vc4u.models import Profile
# Create your views here.

def index(request):
user_list = Profile.objects.order_by('name')
context_dict = {'user_list': user_list}

return render(request, 'index.html', context_dict)


index.html

<div class="container">
{% if user_list %}
<table class="table table-bordered table-striped" id="users">
<tr>
<th>Name</th>
<th>Email</th>
<th>City</th>
</tr>
{% for users in user_list %}
<tr>
<td>{{ users.name }}</td>
<td>{{ users.email }}</td>
<td>{{ users.city }}</td>
</tr>
{% endfor %}
</table>
{% else %}
<strong>There are no users.</strong>
{% endif %}
</div>


I ve posted the CSS CDN on top of the page and the jquery and datatable js CDN on the bottom of the page with this script:

$(document).ready(function(){
$('#users').DataTable();
});


This doesn't seem to work and I had a look at the console in developer tools and no errors are listed.

Answer

From the datatables manual:

For DataTables to be able to enhance an HTML table, the table must be valid, well formatted HTML, with a header (thead) and a body (tbody). An optional footer (tfoot) can also be used.

so your table is missing the required thead and tbody tags.