【问题标题】:django_tables2 Table Meta row attributes are not displayeddjango_tables2 Table Meta 行属性不显示
【发布时间】:2019-02-09 04:12:35
【问题描述】:

我在我的项目中使用django_tables2 库并尝试实现一个表,其中每一行都将拥有一个data-item-name 属性。我的特定表继承自我的 BaseTable 类,而后者又继承自 django_tables2.Table 类。代码如下:

page_table.py

import django_tables2 as tables

from django.utils.html import format_html

from myapp.utils.base_table import BaseTable
from myapp.models import MyModel

class PageTable(BaseTable):
    item_id = tables.Column(accessor='pk')

    # This method works perfectly fine as expected
    def render_item_name(self, record):
        return format_html(
            '<span data-item-id="{0}">{1}</span>'.format(
                record.item_id,
                record.item_name
            )
        )

    class Meta:
        model = MyModel
        # When debugging this attribute is accessed only on booting up
        # And is ignored when I for example first visit or refresh the page
        row_attrs={
            'data-item-name': lambda r: r.item_name
        }
        fields = (
            'item_id',
            'item_name',
            'item_description',
            'item_price', # etc
        )

base_table.py

from django_tables2 import Table

class BaseTable(Table):
    def __init__(self, *args, **kwargs):
        super(BaseTable, self).__init__(*args, **kwargs)

虽然表格呈现没有错误并且没有任何中断,但表格中的单行上没有data-item-name 属性,尽管据我浏览文档,据说在表格中声明此属性元类就足够了。我错了还是我错过了什么?任何帮助将不胜感激。

附:我正在使用 Python 2.7、Django 1.8.17 和 django-tables2 v. 1.16.0

【问题讨论】:

  • 由于某种原因,当我在 lambda 表达式中将 r 更改为 record 时,它现在正在工作。有人可以给我一个解释吗?因为我没看懂:(

标签: python django django-tables2


【解决方案1】:

Django 表使用(也与 Django 一样)metaclasses 来分解表类,这就是您在调试器中看到此类行仅在启动时被击中的原因仅在启动时,因为当类为正在创建您的表。

另一方面,当您自定义行属性时,django-tables2(根据设计)为行中的当前数据命名为 record

您可以在docs阅读:

默认情况下,为行提供奇数和偶数类名,可以使用 row_attrs Table.Meta 属性或作为 Table 构造函数的参数进行自定义。将只添加类似字符串的值,将使用可选的关键字参数 record 调用可调用对象,并将添加返回值。例如。

【讨论】:

  • 谢谢,这解释了很多!我想我应该更仔细地阅读文档。
猜你喜欢
  • 2013-10-24
  • 1970-01-01
  • 2013-06-21
  • 2021-12-29
  • 2015-07-23
  • 1970-01-01
  • 2012-03-01
  • 1970-01-01
  • 2011-07-11
相关资源
最近更新 更多