Python - How To Use DataTables With Django

In this tutorial we will try to use jQuery DataTables With Django Web Framework. Django is an advanced Web framework written in Python that makes use of the model view controller (MVC) architectural pattern. The official project site describes Django as "a high-level Python Web framework that encourages rapid development and clean, pragmatic design. And It’s free and open source to every developer in the world. Getting Started First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/. Next is to download Data Tables. DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool,that is easy to use and convinient. Here is the link for Data Tables Plugins https://datatables.net/ After Python IDLE's is installed, open the command prompt then type "pip install Django", and hit enter. tut1 Wait for the django to be downloaded and installed at the same time. Then After that type "python -m django version" and hit enter to check if django is installed and what version of django is. tut2Creating the App After setting django we will now create the web app for the web server. First create a new folder named "Python - How To Use DataTables With Django", then cd to a newly created folder, then type "django-admin startproject main" and hit enter. A new folder will be created on the directory named 'main'. tut3Running The Server After creating a project, cd to the newly created directory, then type "manage.py runserver" and hit enter to start the server running. The "manage.py" is a command of django-admin that utilize the administrative tasks of python web framework. Here is the image of python web server: tut4Note: Type '127.0.0.1:8000' in the url browser to view the server. When there is code changes in the server just (ctrl + C) to command prompt to stop the server from running, then start again to avoid errors. Creating The Website This time will now create the web app to display the web models. First locate the directory of the app via command prompt cd, then type "manage.py startapp table" and hit enter. A new directory will be create inside the app named "table". tut5Setting up The URL This time will now create a url address to connect the app from the server. First Go to main directory, then open urls via Python IDLE's or any text editor. Then import "include" module beside the url module and import additional module to make a redirect url to your site "from main import views". After that copy/paste the code below inside the urlpatterns.
  1. url(r'^$', views.index_redirect, name='index_redirect'),
  2. url(r'^table/', include('table.urls')),
It will be look like this:
  1. from django.conf.urls import include, url
  2. from django.contrib import admin
  3. from main import views
  4.  
  5. urlpatterns = [
  6. url(r'^$', views.index_redirect, name='index_redirect'),
  7. url(r'^table/', include('table.urls')),
  8. url(r'^admin/', admin.site.urls),
  9. ]
Then after that create a view that will catch the redirect url. To do that create a file "views.py" then copy/paste the code below and save it as "views.py".
  1. from django.shortcuts import redirect
  2.  
  3. def index_redirect(request):
  4. return redirect('/table/')
Creating The Path For The Pages Now that we set the connect we will now create a path for the web pages. All you have to do first is to go to table directory, then copy/paste the code below and save it inside "table" directory named 'urls.py' The file name must be urls.py or else there will be an error in the code.
  1. from django.conf.urls import url
  2. from . import views
  3.  
  4. urlpatterns = [
  5. url(r'^$', views.index, name='index'),
Creating A Static Folder This time we will create a directory to import the statics and templates. First go to the registration directory then create a directory called "static", after that create a sub directory called "table". You'll notice that it is the same as your main app directory name, to assure the absolute link. This is where you import the css, js, etc directory. Creating The Views The views contains the interface of the website. This is where you assign the html code for rendering it to django framework. To do that first open the views.py, the copy/paste the code below.
  1. from django.shortcuts import render
  2. from .models import Member
  3.  
  4. # Create your views here.
  5.  
  6. def index(request):
  7. all_members = Member.objects.all()
  8. return render(request, 'table/index.html', {'all_members': all_members})
Creating The Models Now that we're done with the views we will then create a models. Models is module that will store the database information to django. To do that locate and go to table directory, then open the "models.py" after that copy/paste the code.
  1. from django.db import models
  2.  
  3. # Create your models here.
  4.  
  5. class Member(models.Model):
  6. firstname = models.CharField(max_length=20)
  7. lastname = models.CharField(max_length=20)
  8. age = models.CharField(max_length=3)
  9. email = models.EmailField(max_length=50)
  10. address = models.CharField(max_length=50)
  11.  
  12. def __str__(self):
  13. return self.firstname + " " + self.lastname
After that go to table directory then open "admin.py" and copy/paste the code below.
  1. from django.contrib import admin
  2. from table.models import Member
  3. # Register your models here.
  4.  
  5. admin.site.register(Member)
Registering The App To The Server Now that we created the interface we will now then register the app to the server. To do that go to the main directory, then open "settings.py" via Python IDLE's or any text editor. Then copy/paste this script inside the INSTALLED_APP variables 'table'. It will be like this:
  1. INSTALLED_APPS = [
  2. 'table',
  3. 'django.contrib.admin',
  4. 'django.contrib.auth',
  5. 'django.contrib.contenttypes',
  6. 'django.contrib.sessions',
  7. 'django.contrib.messages',
  8. 'django.contrib.staticfiles',
  9. ]
Creating An Account After registering the app we will now create a user account that will login to the server. To do that cd to "main" directory, then type "manage.py createsuperuser" and hit enter. Fill up the required field to make to your registration ready. tut6Storing Information To The Database After creating the account, run the server again then type "http://127.0.0.1:8000/admin" on the url address and hit enter. You notice that you are directed in the django admin login page, try to login your newly created account. tut7 After logging in click Members then fill up the required field that will be later display in the table. Creating The Mark up Language Now we will create the html interface for the django framework. First go to table directory, then create a directory called "templates" and create a sub directory on it called table. base.html
  1. <!DOCTYPE html>
  2. <html lang = "en">
  3. <head>
  4. <meta charset = "urf-8" name = "viewport" content = "width=device-width, initial-scale=1"/>
  5. {% load static %}
  6. <link rel = "stylesheet" type = "text/css" href = "{% static 'table/css/bootstrap.css' %}"/>
  7. <link rel = "stylesheet" type = "text/css" href = "{% static 'table/css/jquery.dataTables.css' %}"/>
  8. </head>
  9. <nav class = "navbar navbar-default" >
  10. <div class = "container-fluid">
  11. <a class = "navbar-brand ">Sourcecodester</a>
  12. </div>
  13. </nav>
  14. <div class = "col-md-3"></div>
  15. <div class = "col-md-6 well">
  16. <h3 class = "text-primary">Python - How To Use DataTables With Django</h3>
  17. <hr style = "border-top:1px dotted #000;"/>
  18. {% block body %}
  19. {% endblock %}
  20. </div>
  21.  
  22. </body>
  23. <script src = "{% static 'table/js/jquery-3.2.1.js' %}"></script>
  24. <script src = "{% static 'table/js/jquery.dataTables.js' %}"></script>
  25. <script type = "text/javascript">
  26. $(document).ready(function(){
  27. $('#table').DataTable();
  28. });
  29. </html>
Save it as "base.html" inside the table directory "sub directory of templates". index.html
  1. {% extends 'table/base.html' %}
  2. {% block body %}
  3. <table id = "table" class = "table table-bordered">
  4. <thead class = "alert-success">
  5. <tr>
  6. <th>Firstname</th>
  7. <th>Lastname</th>
  8. <th>Age</th>
  9. <th>Email</th>
  10. <th>Address</th>
  11. </tr>
  12. </thead>
  13. {% for member in all_members %}
  14. <tr>
  15. <td>{{ member.firstname }}</td>
  16. <td>{{ member.lastname }}</td>
  17. <td>{{ member.age }}</td>
  18. <td>{{ member.email }}</td>
  19. <td>{{ member.address }}</td>
  20. </tr>
  21. {% endfor %}
  22. </tbody>
  23. </table>
  24.  
  25. {% endblock %}
Migrating The App To The Server Now that we done in setting up all the necessary needed, we will now then make a migration and migrate the app to the server at the same time. To do that open the command prompt then cd to the "main" directory, then type "manage.py makemigrations" and hit enter. After that type again "manage.py migrate" then hit enter. tut8 Now try to run the server again, and see if all things are done. There you have it we successfully implement jQuery DataTables With Django Web Framework. I hope that this simple tutorial help you for what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!!

Add new comment