为 django-tables2 设置空文本行为

Ron*_*man 1 django-tables2

我的 django 表中的某些列碰巧是空的,因此在那里呈现的文本是“无”。我想看到一个空白区域。

django tables2 有一些关于这个主题的文档,但我不完全理解。我必须在哪里定义这个 empty_text 行为参数?在相关的类元中尝试过,但显然没有效果。

lit*_*die 5

您可以覆盖列定义中的默认值。

如果您没有明确声明您的列(例如,您让 table2 从您的模型中找出它),那么您将必须定义它,以便您可以为其设置选项。可以对来自模型的数据执行此操作。只要您定义的列名称与模型字段名称匹配,它就会匹配它们。

class TableClass(tables.Table):
    mycolumn = tables.Column(default=' ')
Run Code Online (Sandbox Code Playgroud)

如果您需要逐行动态计算默认值,请定义您的列并传递 empty_values=[],例如:

class TableClass(tables.Table):
    mycolumn = tables.Column(empty_values=[])
Run Code Online (Sandbox Code Playgroud)

这告诉tables2它不应将任何值视为“空”..然后您可以为该列声明自定义呈现方法:

def render_mycolumn(value):
    # This is a very simplified example, you will have to work out your
    # own test for blankness, depending on your data.  And, if you are
    # returning html, you need to wrap it in mark_safe() 
    if not value:
        return 'Nobody Home'
    return value
Run Code Online (Sandbox Code Playgroud)

请记住,render_如果 tables2 认为该值为空,则不会调用方法,因此您还必须设置empty_values=[].

这是描述自定义渲染方法如何工作的tables2文档:http ://django-tables2.readthedocs.org/en/latest/pages/custom-rendering.html?highlight=empty#table-render-foo-method