Conditional statements in Django_tables2 class definition
Asked Answered
R

1

4

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": ""
            }
Runge answered 19/2, 2021 at 13:48 Comment(0)
N
6

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.

Nocti answered 19/2, 2021 at 21:14 Comment(2)
I had some "elif"s to write but I managed to work with that with some nesting. Is there any way to use standard function, not lambda in that case?Runge
@Runge - added a second example using a functionNocti

© 2022 - 2024 — McMap. All rights reserved.