【发布时间】: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