Django – Showing model data directly into table with sorting and pagination


In this article, we will see how to make a table in Django which will render model data. We are not going to use the <table> tag of html. We will use a simple Django table library which provides features to directly show Django model data in a table with pagination feature.

Example

First of all, create a project and an app and set up the urls.

Install the django_tables2 package −

pip install django_tables2

In settings.py

INSTALLED_APPS+=["django_tables2"]

In models.py, create a simple model for testing −

from django.db import models

# Create your models here.
class Data(models.Model):
   Name=models.CharField(max_length=100)
   salary = models.CharField(max_length=20)

In urls.py, add a url and render a table view −

from django.urls import path
from . import views

urlpatterns = [
   path('table',views.TableView.as_view(),name='table')
]

Now in views.py, add the following lines −

from .models import Data
# Create your views here.
import django_tables2 as tables

# this class will create the table just like how we create forms
class SimpleTable(tables.Table):
   class Meta:
      model = Data

# this will render table
class TableView(tables.SingleTableView):
   table_class = SimpleTable
   queryset = Data.objects.all()
   template_name = "table_example.html"

Here we created a table of model Data and then a view where we defined a table and a query. We can use filter queries here and a template where we are going to show the table.

Create the templates folder and add table_example.html in it with the following lines −

{% include 'material/includes/material_css.html' %}
{% include 'material/includes/material_js.html' %}
<!DOCTYPE html>
<html>
   <head>
      <title>TUT</title>
   </head>
   <body>
      # these two will render the table
      {% load django_tables2 %}
      {% render_table table %}
   </body>
</html>

Here we loaded some default designs and django_tables2 library and then rendered the table that we made in views.

Now, let's proceed to check the output.

Output

Updated on: 26-Aug-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements