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.
I would like commune
to be rendered bold and green if confiance_commune
is true.
Here is my code :
models.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
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.
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)