简体   繁体   English

使用基于另一个布尔列的 Django-Tables2 格式化列

[英]Format Column with Django-Tables2 based on another boolean column

I have a table whith a few columns amongst them one is called commune and has a string type and another is confiance_commune which is a boolean value.我有一个表,其中有几列,其中一个称为commune ,具有字符串类型,另一个是confiance_commune ,它是一个布尔值。

I would like commune to be rendered bold and green if confiance_commune is true.如果confiance_commune是真的,我希望commune变得大胆和绿色。

Here is my code :这是我的代码:

models.py模型.py

class Mrae(models.Model):
    titre = models.TextField(blank=True, null=True)
    lien = models.TextField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    type_projet = models.TextField(blank=True, null=True)
    pv_mentionne = models.BooleanField(blank=True, null=True)
    commune = models.TextField(blank=True, null=True)
    commune_m = models.TextField(blank=True, null=True)
    departement = models.IntegerField(blank=True, null=True)
    date = models.DateField(blank=True, null=True)
    confiance_commune = models.BooleanField(blank=True, null=True)
    index = models.AutoField(primary_key=True)

    class Meta:
        managed = False
        db_table = 'mrae'

tables.py表.py

from django_tables2 import tables
from django_tables2.columns import URLColumn
from .models import Mrae

class MraeTable(tables.Table):
    
    lien = URLColumn("Lien") 
    
    class Meta:
        model = Mrae
        attrs = {"class": "table table-responsive"}
        fields = ['titre', 'lien', 'pv_mentionne', 'date', 'commune', 'departement']
        tamplate_name = "django_tables2/bootstrap-responsive.html"

You can use the custom render function calling with the record, then just create a simple if statement that checks the confiance_commune attribute to set the style for the commune data.您可以使用自定义渲染函数调用记录,然后只需创建一个简单的 if 语句来检查confiance_commune属性以设置commune数据的样式。

https://django-tables2.readthedocs.io/en/latest/pages/custom-data.html#table-render-foo-methods https://django-tables2.readthedocs.io/en/latest/pages/custom-data.html#table-render-foo-methods

class MraeTable(tables.Table):
    
    lien = URLColumn("Lien") 
    
    class Meta:
        model = Mrae
        attrs = {"class": "table table-responsive"}
        fields = ['titre', 'lien', 'pv_mentionne', 'date', 'commune', 'departement']
        template_name = "django_tables2/bootstrap-responsive.html"

    def render_commune(self, record):
        if record.confiance_commune:
            return format_html(
                    "<span style='color:green;font-weight:bold;'>{}</span>", 
                    mark_safe(record.commune)
                )
        return mark_safe(record.commune)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM