如何在python Django中更改特定行的背景色

2024-09-30 06:11:29 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码是table.py

 class StColumn(tables.Column):
     def render(self, value, record):
       if record.status == 'warning':
          self.attrs ={"td": {"bgcolor": "DeepSkyBlue"}}
      elif record.status == 'ok':
          self.attrs ={"td": {"bgcolor": "SandyBrown"}}
      return u"%s" % (record.status.id)
class resultTable(BaseTable):
class Meta(BaseTable.Meta):
    model = resultModel
    attrs = {'class': 'table table-striped table-bordered table-hover row-color=green' , 'width': '70%'}
    status= StColumn(accessor='status.id')
    print(status)
    fields = (
        "field1",
        "field2",
        "field3",
        "status",
        "field5",
    )

**当状态==警告和状态==正常时,我们如何更改行的颜色**


Tags: 代码pyselfid状态statustablerecord
1条回答
网友
1楼 · 发布于 2024-09-30 06:11:29

显示逻辑不应在视图中处理,而应在模板中处理。有关更多信息,请参阅本文档:

https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#if

通常,您会通过使用视图和HTML模板来显示模型中的数据。您将编写一个视图函数/类,当用户转到特定URL时,该函数/类将被调用。该视图将使用查询集将数据从模型传递到模板中。在这里讨论这么多细节是非常浪费的,因为有大量的文档可以描述这个过程

基本上,您需要这样的视图:

def your_view(request):
    your_instances = YourModel.objects.all()
    context = {
        'your_instances': your_instances,
    }
    return render(request, 'your_html_template.html', context=context)

然后,您的模板将如下所示:

<table>
  {% for instance in your_instances %}
    {% if instance.status == 'warning' %}
      <tr style="background-color:#FF0000">
    {% endif %}
    {% if instance.status == 'ok' %}
      <tr style="background-color:#000000">
    {% endif %}
        <td>{{ instance.field }}</td>
      </tr>
  {% endfor %}
</table>

相关问题 更多 >

    热门问题