【问题标题】:Transpose Django Table in django_tables2在 django_tables2 中转置 Django 表
【发布时间】:2011-08-01 14:12:45
【问题描述】:

我正在尝试制作一个视图,基本上显示有关这样的记录的信息

|Description| blahblahblah
|Name       | blah blah blahs
|Last Edited| someDate
|Owned by   | Blah blah blah info

这是从 django_tables2 默认呈现表的方式转置的。有没有一种简单的方法可以做到这一点,还是我必须编写自己的模板?我发现这样做(理论上)因为有一个很好的自定义模板示例,它说我必须“将您的 Table 子类的实例传递到您自己的模板中,并自己渲染它”。虽然我实际上并不知道这是什么意思:(

【问题讨论】:

    标签: django django-tables2


    【解决方案1】:

    您需要编写自己的模板,通过迭代表的属性并编写正确的标签来生成所需的 HTML。用于as_html() 函数的模板是一个很好的例子,说明你如何做到这一点:https://github.com/bradleyayers/django-tables2/blob/master/django_tables2/templates/django_tables2/table.html

    【讨论】:

      【解决方案2】:

      我今天为一个项目解决了这个问题,它实际上相当简单。

      定义一个新表

      tables.py 内,定义一个包含两列的表格。我们称第一列为name,第二列为value

      class RowTable(tables.Table):
          name = tables.Column()
          value = tables.Column()
      
          class Meta:
              template = 'django_tables2/bootstrap.html'
              attrs = {'class': 'table table-striped table-responsive'}  
      

      在你看来,将数据绑定到表

      然后,在您看来,您需要从数据库中提取实例(行),并使用字典填充表:

      row_instance = Model.objects.get(foo=foo.id)
      #Extract column data from instance be sure it is string!
      height = str(row_instance.height)
      weight = str(row_instance.weight)
      nationality = row_instance.nationality
      
      #Create dictionary of data in form table will recognize
      row_data =[ {'name': 'height', 'value': height},
                  {'name': 'weight', 'value': weight},
                  {'name': 'nationality', 'value': nationality} ]
      
      #Bind to table and configure
      table = RowTable(row_data)
      

      然后像往常一样配置表格,放入上下文并发送到模板。您将拥有一个包含两列的表,其中显示了数据库行中的所有数据。

      【讨论】:

        【解决方案3】:

        将/lib/python2.7/site-packages/django/contrib/admin/templatetags/admin_list.py中的result_list(cl)函数改成这样:

        def result_list(cl):
         """
         Displays the headers and data list together
         """
         headers = list(result_headers(cl))
         num_sorted_fields = 0
         for h in headers:
             if h['sortable'] and h['sorted']:
                 num_sorted_fields += 1
         result1 = list(results(cl))
         result2 = map(list, zip(*result1))
         return {'cl': cl,
                 'result_hidden_fields': list(result_hidden_fields(cl)),
                 'result_headers': headers,
                 'num_sorted_fields': num_sorted_fields,
                 'results': result2}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-02-21
          • 2014-02-04
          • 2019-03-23
          • 2013-05-23
          • 2023-03-16
          • 1970-01-01
          相关资源
          最近更新 更多