Search code examples
pythondjangodjango-tables2

Django-tables2 - can't I use [A('argument')] inside the "text" parameter?


I'm trying to make this table with a clickable field which changes the boolean for the entry to its opposite value. It works, but I want an alternative text as "False" or "True" does not look nice, and the users are mainly Norwegian.

def bool_to_norwegian(boolean):
    if boolean:
        return "Ja"
    else:
        return "Nei"


class OrderTable(tables.Table):

    id = tables.LinkColumn('admin_detail', args=[A('id')])
    name = tables.Column()
    address = tables.Column()
    order = tables.Column()
    order_placed_at = tables.DateTimeColumn()
    order_delivery_at = tables.DateColumn()
    price = tables.Column()
    comment = tables.Column()
    sent = tables.LinkColumn('status_sent', args=[A('id')])
    paid = tables.LinkColumn('status_paid', args=[A('id')], text=[A('paid')])

    class Meta:
        attrs = {'class': 'order-table'}

If you look under the "paid" entry I am testing this right now, why can't I access the data with the same accessor as I do in the args? If I change the args to args=[A('paid')] and look at the link, it does indeed have the correct data on it. The model names are the same as the ones in this table, and "paid" and "sent" are BooleanFields.

This is kind of what I ultimately want:

text=bool_to_norwegian([A('paid')])

Here is what I send to the table:

orders = Order.objects.order_by("-order_delivery_at")
orders = orders.values()
table = OrderTable(orders)
RequestConfig(request).configure(table)

Solution

  • The text argument expects a callable that accepts a record, and returns a text value. You are passing it a list (which it will just ignore), and your function is expecting a boolean instead of a record. There is also no need for using accessors here.

    Something like this should work:

    def bool_to_norwegian(record):
        if record.paid:
            return "Ja"
        else:
            return "Nei"
    

    Then in your column:

    paid = tables.LinkColumn('status_paid', text=bool_to_norwegian)
    

    (Note, it is not clear from your question where the data is coming from - is paid a boolean? You may need to adjust this to fit).

    As an aside, the way you are passing args to your columns is weird (it seems the documentation also recommends this, but I don't understand why - it's very confusing). A more standard approach would be:

    id = tables.LinkColumn('admin_detail', A('id'))
    

    or using named arguments:

    id = tables.LinkColumn('admin_detail', accessor=A('id'))