ในบทความนี้จะดูวิธีสร้างตารางใน Django ที่แสดงข้อมูลโมเดล ไม่ใช้แท็ก <table> ของ HTML แต่ใช้ไลบรารี django_tables2 ที่ให้ฟีเจอร์แสดงข้อมูลโมเดลเป็นตารางพร้อม pagination โดยตรง
ตัวอย่าง
สร้างโปรเจกต์และแอป ตั้งค่า urls
ติดตั้ง django_tables2:
pip install django_tables2
ใน settings.py:
INSTALLED_APPS+=["django_tables2"]
ใน models.py สร้างโมเดลทดสอบ:
from django.db import models
class Data(models.Model):
Name = models.CharField(max_length=100)
salary = models.CharField(max_length=20)
ใน urls.py เพิ่ม URL และ render table view:
from django.urls import path
from . import views
urlpatterns = [
path('table', views.TableView.as_view(), name='table')
]
ใน views.py:
from .models import Data
import django_tables2 as tables
class SimpleTable(tables.Table):
class Meta:
model = Data
class TableView(tables.SingleTableView):
table_class = SimpleTable
queryset = Data.objects.all()
template_name = "table_example.html"
สร้างตารางจากโมเดล Data และ View ที่กำหนด table, queryset, template
สร้างโฟลเดอร์ templates และไฟล์ table_example.html:
{% include 'material/includes/material_css.html' %}
{% include 'material/includes/material_js.html' %}
<!DOCTYPE html> <html>
<head> <title>TUT</title> </head>
<body>
{% load django_tables2 %}
{% render_table table %}
</body> </html>
โหลดไลบรารีและ render ตาราง
เอาต์พุต
