我向你推荐一个非常好的 Django 应用程序,名为“Django Tables2”
Django Tables Documentation
安装后,您需要将 django_tables2 添加到已安装的应用中
它们非常易于使用,您需要在与您的 settings.py models.py 相同的文件夹中创建一个文件 tables.py...
在这个 tables.py 文件中,您必须使用您的模型之一添加一个新表,例如:
import django_tables2 as tables
from models import *
class DeviceTable(tables.Table):
# row_id used to have each ID in a first hidden row
row_id = tables.columns.TemplateColumn(attrs={'cell': {'style':'display:none'}}, template_code=u'<span id="row_id_{{ record.id }}">', orderable=False, verbose_name=u'Row ID')
name = tables.columns.TemplateColumn(template_code=u'{{ record.dev_name }}', orderable=True, verbose_name=u'Device Name'))
checkbox = tables.columns.TemplateColumn(template_code=u'<input type="checkbox" >',orderable=False, verbose_name=u'Checkbox')
class Meta:
model = Device
attrs = {'class': 'myClass'} #Add table classes here
fields = ('row_id', 'name', 'track_no', 'dev_type','checkbox')
sequence = fields
order_by = ('name', )
您可以自定义字段或添加新字段,文档解释得很好。创建表格后,您需要在视图中加载表格:
from django_tables2 import RequestConfig
from tables import DeviceTable
def yourView(request, ...):
# ... Your actual code ...
# We get the object list
device_list = Device.objects.all()
# We pass the object list to the table
table = DeviceTable(device_list)
# RequestConfig is used to automatically add pagination to the table
RequestConfig(request, paginate={"per_page": 10}).configure(table)
return render_to_response('your_template.html', {'table': table, }, context_instance=RequestContext(request))
要在模板中渲染这个表格,你需要加载 template_tag 来渲染表格:
{% load render_table from django_tables2 %}
# ... Your other code ...
<div class="col-md-12">
{% render_table table %}
</div>