django - 在Django框架中将数据从数据库提取到表中

标签 django database python-3.x django-forms html-table

如何在 django 中将数据从数据库提取到 HTML 表?

我已经构建了我的模型。

class device:
    track_no=models.CharField(max_length=100)
    dev_type=models.CharField(max_length=50)
    dev_name=models.CharField(max_length = 100)

我想制作一个表单,可以在其中使用“设备”表的数据填充表。另外,我想在表中添加一个额外的字段作为每行前面的复选框。 请提及所需的所有文件。

最佳答案

我向您推荐一个非常好的 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', )

您可以自定义字段或添加新字段,文档对此进行了很好的解释。创建表格后,您需要在 View 中加载表格:

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>

关于django - 在Django框架中将数据从数据库提取到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29691838/

相关文章:

Django 创建唯一函数索引

java - 如何在应用程序部署后立即打开所有连接?

xml - 数据库 XPath 查询

python - 日期转换器

python - 如何评估字典键是否在字符串中

python - Django 重定向 http -> https

django - Windows OS上的Django Haystack + ElasticSearch实现

python - 一段时间后,将 Django 的 collectstatic 与 boto S3 一起使用会抛出 "Error 32: Broken Pipe"

sql - SQL Server中时间字段求和的方法

python - 使用多个元组管理多个列表