2015-04-17 26 views
1

如何將數據從數據庫中拉到django中的HTML表中?將數據從數據庫中提取到Django框架中的表

我已經建立了我的模型。

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

我想製作一個表格,我可以用「設備」表的數據填充表格。此外,我希望表中的額外字段作爲每行前面的複選框。 請提及所有需要的文件。

+0

所有這一切已發佈的是一個程序說明。但是,我們需要您[提問](http:// $ SITEURL $/help /如何提問)。我們無法確定您想從我們這裏得到什麼。請[編輯]您的帖子以包含我們可以回答的有效問題。提醒:確保你知道[這裏的主題是什麼](http:// $ SITEURL $/help/on-topic),要求我們爲你寫程序,建議不在話下。 – Dustin

回答

1

我建議你所謂的 「Django的Tables2」

Django Tables Documentation

你已經安裝了它之後,你需要django_tables2添加到您安裝的應用程序很好的Django應用程序

它們非常易於使用,您需要在與settings.py相同的文件夾中創建一個文件tables.py models.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> 
+1

非常感謝。 – atitpatel

相關問題