Sunday, 24 July 2016

Using Bootstrap Datatables with Django [How To]

Datatables is a Jquery plugin that allows you to create awesome tables, with functionalities such as searching, sorting the table by a specific column,pagination of large amounts of data etc: all working out of the box. In this tutorial, we will create a simple Django Application and use datatables to show some data. So let's begin:

Django Project Setup



Open your terminal. Create a new Django project by typing:
django-admin startproject dataTableExample

Then, create an app named myApp:
cd dataTableExample
django-admin startapp myApp

Now, add this app to our project by adding 'myApp' in the list of INSTALLED_APPS in dataTableExample/settings.py. You can use vim, sublime-text or any other text editor. Now, our INSTALLED_APPS section in settings.py looks like this:

Datatables with Django

Let's create a model to store student record data. Open myApp/models.py and add the following lines:
class studentRecord(models.Model):
    roll = models.IntegerField(unique=True)
    Name = models.CharField(max_length = 50)
    section = models.CharField(max_length = 20)

Run the following commands to create the required tables in the database:
python manage.py makemigrations
python manage.py migrate

Let's create a url to display the table. In dataTableExample/urls.py, import the views.py file as:
from myApp import views

Add the details/ url to urlpatterns[]:
url(r'^details/', views.Details),

Now, let's create the Details view. Add the following code to myApp/views.py:
from myApp import views

Now add the details/ url to urlpatterns[]:
url(r'^details/', views.Details),

Now, let's create the Details view. Add the following code to myApp/views.py:
from django.shortcuts import render_to_response
from myApp import models

def Details(request):
    c = {}
    students = models.studentRecord.objects.all()
    c['students'] = students
    return render_to_response('details.html',c)

Now, we need to specify the directory where our template will be stored. Open dataTableExample/settings.py and inside the TEMPLATES section, change the 'DIRS' so that it looks like this:
'DIRS': [ BASE_DIR + '/templates/', ],

Now, create a folder called templates and insert the following code inside templates/details.html:
 <html>
   <head>
     <meta charset="utf-8">
     <title>Student Details</title>
   </head>
   <body>
     <div class='container'>
       <table id = 'studentRecords' class='table table-hover table-striped'>
         <thead>
           <tr>
             <th>Roll No</th>
             <th>Name</th>
             <th>Section</th>
           </tr>
         </thead>
         <tfoot>
         </tfoot>
         <tbody>
           {% for student in students %}
             <tr>
               <td>{{ student.roll }}</td>
               <td>{{ student.Name }}</td>
               <td>{{ student.section }}</td>
             </tr>
           {% endfor %}
         </tbody>
       </table>
     </div>
   </body>
 </html>

It's time to create some sample studentRecord objects. In your terminal, type python manage.py shell to access the Django shell. Now type the following:
from myApp import models
o = models.studentRecord(roll=1,Name='nikhil',section=2)
o.save()
o = models.studentRecord(roll=2,Name='john',section=1)
o.save()
o = models.studentRecord(roll=3,Name='jane',section=3)
o.save()
quit

Fire up your server by typing:
python manage.py runserver

Open up your browser and browse to http://localhost:8000/details/
You will see the entered records.

Datatables with Django



Bootstrap & Datatables Integration



Now, inside details.html, import the required bootstrap and datatable files by adding the following lines inside the <head>...</head> tags:
<!-- Datatables and Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<link href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" rel="stylesheet" type="text/css" media="screen" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="//code.jquery.com/jquery-1.12.3.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>

We need to tell datatables which table we are using. After the </body> tag, add the following code:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#studentRecords').DataTable();
} );
</script>

Save the file and reload the webpage in your browser. And voila! The old, boring table is replaced by a more functional table. Try searching the table by typing some text in the search box:

Datatables with Django



You can sort the rows by clicking on any column heading (here, the rows are sorted by name):

Datatables with django



Also, for huge amounts of data, it will implement pagination by itself. So you can dynamically update the table rows using Ajax, which will help improve the performance significantly.

Click here to learn more about datatables on their official website.
This project is available on my github repo too.

3 comments:

  1. Thanks for this very interesting and works well. Out of interest if you want to link to a detail view say on the name column how would you go about this if you are using get absolute url in your model?

    ReplyDelete
  2. @disqus_6rAVWa7tpZ:disqus thanks. I haven't used generic class based views much but I think it should work fine with the code similar to the above code. Just use your objectname instead of student. Since I am using client side script for Datatables it is not much dependent on how you are getting the objects from the server side into your template.

    ReplyDelete
  3. […] instance, we created a simple Student Record Management project in our previous tutorial about datatables. Let’s say, we want that software for all the classes in our school. Or say, we want to […]

    ReplyDelete