DataTablesとDjango(model)の連携
前回(Djangoを使ってみる⑤(DBの中身を表示) - doramochi blog)DBの中身を表示してみたが、あのままでは少し味気ないので他の方法を試してみる。
DataTablesとDjango(model)の連携
DataTablesについて
今回使用するDataTables:DataTables | Table plug-in for jQuery
・ページング機能
・ソート機能
・検索機能
などが搭載されたテーブルを手軽に使うことが出来る。
データ量が多い場合はServer-side processingを使うと良い。
今回データ量は少ないがServer-side processingを使ってやってみる。
django-datatables-viewのインストール
DjangoでServer Side Processingする場合は、 django-datatables-viewを使う。下記コマンドでインストールしておく。
pip install django-datatables-view
HTMLテンプレートの作成
必要な処理は以下の通り
①DataTablesを使うのに必要なファイルを読み込む
<link rel="stylesheet" href="https://cdn.datatables.net/t/bs-3.3.6/jqc-1.12.0,dt-1.10.11/datatables.min.css"/> <script src="https://cdn.datatables.net/t/bs-3.3.6/jqc-1.12.0,dt-1.10.11/datatables.min.js"></script>
②テーブルを作成する
<table id="book" class="table table-bordered"> <thead> <tr><th>本の名前</th> <th>作者</th> <th>出版社</th> <th>価格</th> </tr> </thead> </table>
③作成したテーブルにDataTablesを適用する
<script> $('#book').DataTable({ オプションを記載 }); </script>
オプションは公式に詳しく載っているので必要なものを記載しておく。
オプション:https://datatables.net/reference/option/
今回はServer-side processing(ajax)を使用するので下記のように設定する。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>書籍一覧</title> <link rel="stylesheet" href="https://cdn.datatables.net/t/bs-3.3.6/jqc-1.12.0,dt-1.10.11/datatables.min.css"/> <script src="https://cdn.datatables.net/t/bs-3.3.6/jqc-1.12.0,dt-1.10.11/datatables.min.js"></script> </head> <body> <table id="book" class="table table-bordered"> <thead> <tr><th>本の名前</th> <th>作者</th> <th>出版社</th> <th>価格</th> </tr> </thead> </table> <script> $('#book').DataTable({ deferRender: true, serverSide: true, processing: true, orderCellsTop: true, responsive: true, ajax: { "url": "/data/", "type": "GET", }, columnDefs: [ {targets: 0, data: 'book_name'}, {targets: 1, data: 'author' }, {targets: 2, data: 'publisher' }, {targets: 3, data: 'price' }, ] }); </script> </body> </html>
views.pyの編集
先ほど設定したテーブルにmodelのデータを渡すための処理を追加する。
これまでと違い「class」にしなければいけないので注意。
from django_datatables_view.base_datatable_view import BaseDatatableView class DataTableView(BaseDatatableView): # モデルの指定 model = book_list # 表示するフィールドの指定 columns = ['book_name', 'author', 'publisher', 'price'] # 検索方法の指定:部分一致 def get_filter_method(self): return super().FILTER_ICONTAINS
ソース全体はこちらを参照:
https://github.com/doramochi00/django/blob/2e1fb25380f567f96e764a91cdbec71b4282742c/test_app/views.py
urls.pyの編集
htmlファイルを読み込むための処理と先ほどのviews.pyに記載した処理を紐づけるための処理を記載する。
from django.urls import path from django.views.generic import TemplateView from .views import DataTableView #追加部分 from . import views urlpatterns = [ path('', views.index, name='index'), path('book_list/', views.view_book_list, name='book_list'), path('book_list_datatables', TemplateView.as_view(template_name='test_app/book_list_datatables.html'), name='book_list_datatables'), #追加部分 path('data/', DataTableView.as_view()), #追加部分 ]
path('data/', DataTableView.as_view()),
の「'data/'」の部分はhtmlファイルに記載した「ajax」のurlの部分と一致させる必要があるので注意。
ajax: { "url": "/data/", "type": "GET", },
動作確認
「python manage.py runserver 127.0.0.1:8000」でサーバを起動させ、
http://127.0.0.1:8000/book_list_datatables
にアクセスをし、下記のように表示されていればOK。
環境一式はこちら:
https://github.com/doramochi00/django/tree/2e1fb25380f567f96e764a91cdbec71b4282742c