django-tables2 - 为 django-tables2 设置空文本行为

标签 django-tables2

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

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

最佳答案

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

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

class TableClass(tables.Table):
    mycolumn = tables.Column(default=' ')

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

class TableClass(tables.Table):
    mycolumn = tables.Column(empty_values=[])

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

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

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

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

关于django-tables2 - 为 django-tables2 设置空文本行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24989473/

相关文章:

django tables2 创建带有链接的额外列

django-filter:使用 request.user 扩展过滤器查询

python - 使用 django_tables2 在 django 中的表中添加 CSS 样式

带有自定义图像单元格的 django-tables2

python - 如何在 django-tables2 中使用基于类的 View 控制分页?

django - 使用 Django-tables2 将 Django 模型导出到 Excel(不同的工作表)

python - 如何使用 django-tables2 动态更改 order_by?

join - 如何使用 django-tables2 连接两个表

css - Django-Tables2 CSS 不工作

python - 如何在 django 1.5 中使用 django_tables2 在基于模型的表中添加 2 个额外的 LinkColumns