ในบทความนี้ เราจะมาดูวิธีการสร้างตารางใน Django ซึ่งจะแสดงข้อมูลโมเดล เราจะไม่ใช้
แท็กของ html เราจะใช้ไลบรารีตาราง Django อย่างง่ายซึ่งมีคุณลักษณะเพื่อแสดงข้อมูลโมเดล Django โดยตรงในตารางที่มีคุณสมบัติการแบ่งหน้าตัวอย่าง
ขั้นแรก สร้างโปรเจ็กต์และแอพ แล้วตั้งค่า URL
ติดตั้ง django_tables2 แพ็คเกจ −
pip install django_tables2
ใน settings.py −
INSTALLED_APPS+=["django_tables2"]
ใน models.py , สร้างแบบจำลองอย่างง่ายสำหรับการทดสอบ −
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)
ใน urls.py เพิ่ม url และแสดงผลมุมมองตาราง -
from django.urls import path from . import views urlpatterns = [ path('table',views.TableView.as_view(),name='table') ]
ตอนนี้อยู่ใน views.py ให้เพิ่มบรรทัดต่อไปนี้ −
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"
ที่นี่ เราสร้างตารางข้อมูลโมเดล จากนั้นเป็นมุมมองที่เรากำหนดตารางและคิวรี เราสามารถใช้การสืบค้นข้อมูลตัวกรองที่นี่และเทมเพลตที่เราจะแสดงตาราง
สร้าง เทมเพลต และเพิ่ม table_example.html ในนั้นด้วยบรรทัดต่อไปนี้ -
{% 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>
ที่นี่เราโหลดการออกแบบเริ่มต้นและ django_tables2 ไลบรารี่แล้วเรนเดอร์ตารางที่เราทำในมุมมอง
ตอนนี้ มาดำเนินการตรวจสอบผลลัพธ์กัน
ผลลัพธ์