【问题标题】:Set background color for a field depending on its value根据字段的值设置字段的背景颜色
【发布时间】:2011-02-19 13:09:20
【问题描述】:

我有一个Customer 表,这里的字段之一是Status....我想根据它的值设置包含此字段的单元格的背景颜色,例如状态为绿色“关闭”;黄色表示状态“待定”等。

最好的方法是什么...如果将来需要,可能会很容易修改?

【问题讨论】:

  • 您能否将Status 值作为单元格上的类并根据需要使用CSS 对其进行着色?

标签: django templates django-templates


【解决方案1】:

在您的 css 为 td 创建类如下,考虑到您希望在 html 表中显示您的客户表信息,

td.closed{ color: green; }
td.pending{ color: yellow; }

现在在您的模板上,您可以在 html 表和 td 上循环您的数据库表,您可以按如下方式调用 css:

<td class="{{ status|lower }}">{{ status }}</td>

希望有帮助

【讨论】:

    【解决方案2】:

    上次我做这样的事情时,我枚举了必须翻译成其他语言的雕像的值,所以我不能依赖于 CSS 中作为类的 status 的字符串值,所以我像这样使用 choices

    在您的models.py 中定义choices

    class SomeModel(models.Model):
        STATUS_CHOICES = (
           (1, _('Pending')),
           (2, _('Closed')),
        )
        status = models.IntegerField(choices=STATUS_CHOICES)
    

    HTML 看起来像这样:

    <td class="color_{{ model_instance.status }}">
        {{ model_instance.status.get_status_display }}
    </td>
    

    你的 CSS 应该类似于:

    td.color_1{ color: green; }
    td.color_2{ color: yellow; }
    

    基本上您可以在不更改 CSS 的情况下更改状态字符串值,例如,如果状态是通过外键连接的枚举值,也可以这样做。还有其他方法可以做到,但在大多数情况下,mmrs151 给出的答案是最简单且足够的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-02
      • 1970-01-01
      • 1970-01-01
      • 2014-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-07
      相关资源
      最近更新 更多