【问题标题】:Pull data from database to tables in Django framework [closed]将数据从数据库拉到Django框架中的表[关闭]
【发布时间】:2015-06-23 20:53:02
【问题描述】:

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)

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

【问题讨论】:

  • 所有发布的都是程序描述。但是,我们需要您ask a question。我们无法确定您想从我们这里得到什么。请edit您的帖子包含一个我们可以回答的有效问题。提醒:请确保您知道what is on-topic here,请我们为您编写程序,建议是题外话。

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


【解决方案1】:

我向你推荐一个非常好的 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多