I am trying to change formatting of my table rows based on one of my object values. I know how to pass row attributes to my template, but don't know how to use current record when deciding how should my row look like in class definition. See below:
class OrderTable(tables.Table):
my_id = tables.Column(verbose_name="Order number")
status = tables.Column(verbose_name="Order status")
class Meta:
model = Order
row_attrs = {
"class": lambda record: record.status
}
This is what I did read in django_tables2 docs. However- When trying to add some 'if's' it seems to return lambda function object instead of value:
class OrderTable(tables.Table):
my_id = tables.Column(verbose_name="Order number")
status = tables.Column(verbose_name="Order status")
class Meta:
model = Order
print(lambda record: record.status)
if lambda record: record.status = '0':
row_attrs = {
"class": "table-success"
}
else:
row_attrs = {
"class": ""
}
What prints in my log is: <function ZamTable.Meta.<lambda> at 0x000001F7743CE430>
I also do not know how to create my own function using 'record' attribute. What should I pass to my newly created function?
class OrderTable(tables.Table):
my_id = tables.Column(verbose_name="Order number")
status = tables.Column(verbose_name="Order status")
class Meta:
model = Order
def check_status(record):
record = record.status
return record
status = check_status(???)
if status = '0':
row_attrs = {
"class": "table-success"
}
else:
row_attrs = {
"class": ""
}
You just need to modify how you are returning the table class value.
row_attrs = {
"class": lambda record: "table-success" if record.status == "0" else ""
}
or as function
def calculate_row_class(**kwargs):
""" callables will be called with optional keyword arguments record and table
https://django-tables2.readthedocs.io/en/stable/pages/column-attributes.html?highlight=row_attrs#row-attributes
"""
record = kwargs.get("record", None)
if record:
return record.status
return ""
class Meta:
model = Order
row_attrs = {
"class": calculate_row_class
}
It also looks like you're not comparing for values correctly, and need to use the double equals instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With