如何在Django中用HTML编写没有数据库的表

时间:2016-10-09 01:48:34

标签: python django django-tables2

我只想在Django中用HTML编写一个表,其中数据不是来自数据库。似乎django-tables2是一个很好的包,我可以在Django中使用。但是,我的数据不是来自数据库,因此可能没有必要使用Django模型。这是我的view.py和HTML页面代码:

def device_manager_submit(request):
    '''Switch manager page'''
    ret = rest.send_device_tor(device_name) #data from rest API exist in the form of array of dictronary: [{}, {}, {}]
    return HttpResponse(ret) #return data to HTML

我可以在HTML中使用for循环来显示这些数据,但我并不清楚如何显示它们:

    <tbody>
        {% for item in xx %} //I'm not sure
        <tr>
            <td>111</td> //how to display?
        </tr>
        {% endfor %}

是否有任何人可以按照HTML页面中的view.py显示数据

2 个答案:

答案 0 :(得分:1)

您不需要返回Django对象来创建模板,您可以使用任何数据。 render()函数允许您将上下文与常规HttpResponse组合在一起。您传递给调用它的视图的请求,要渲染的模板的名称,然后是要提供给模板的数据字典。

def device_manager_submit(request):
    '''Switch manager page'''
    ret = rest.send_device_tor(device_name) #data from rest API exist in the form of array of dictronary: [{}, {}, {}]
    return render(request, 'some_template.html', {'devices': ret}) #return data to HTML

假设ret包含一些namedescription的对象,我们可以像这样循环遍历devices

<tbody>
        {% for device in devices %} 
        <tr>
            <td>{{ device.name }}</td>
            <td>{{ device.description }}</td>
        </tr>
        {% endfor %}

答案 1 :(得分:0)

一种方法是使用pandas加载数据,然后使用import pandas as pd data = [{'column1': 1, 'column2': 2}] df = pd.DataFrame(data) html = df.to_html() 将数据输出到html表中。请参阅以下示例:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>column1</th>
      <th>column2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>1</td>
      <td>2</td>
    </tr>
  </tbody>
</table>

Html将导致:

@api_view(['GET'])
def showData(request):
    data  = [{'column1': 1, 'column2': 2}]
    df = pd.DataFrame(data)
    html = df.to_html()
    return HttpResponse(html)

在Django视图中,这将是:

display
相关问题