Search code examples
pythondjangodjango-tables2

django_tables2 Table Meta row attributes are not displayed


I'm using django_tables2 library in my project and trying to implement a table where each row would possess a data-item-name attribute. My specific table is inherited from my BaseTable class which in its turn is inherited from django_tables2.Table class. Here is the code:

page_table.py

import django_tables2 as tables

from django.utils.html import format_html

from myapp.utils.base_table import BaseTable
from myapp.models import MyModel

class PageTable(BaseTable):
    item_id = tables.Column(accessor='pk')

    # This method works perfectly fine as expected
    def render_item_name(self, record):
        return format_html(
            '<span data-item-id="{0}">{1}</span>'.format(
                record.item_id,
                record.item_name
            )
        )

    class Meta:
        model = MyModel
        # When debugging this attribute is accessed only on booting up
        # And is ignored when I for example first visit or refresh the page
        row_attrs={
            'data-item-name': lambda r: r.item_name
        }
        fields = (
            'item_id',
            'item_name',
            'item_description',
            'item_price', # etc
        )

base_table.py

from django_tables2 import Table

class BaseTable(Table):
    def __init__(self, *args, **kwargs):
        super(BaseTable, self).__init__(*args, **kwargs)

Though the table is rendered without errors and nothing breaks up, there is no data-item-name attribute not on a single row in the table, although as far as I've gone through docs, it's said that declaring this property in table's metaclass is enough. Am I mistaken or is there something I missed in this? Any help would be highly appreciated.

P.S. I'm using Python 2.7, Django 1.8.17 and django-tables2 v. 1.16.0


Solution

  • Django tables use (as Django as well) metaclasses for factoring the table classes that's the reason you see in the debugger that such lines are hitten only on booting up because is when the class for your table is being created.

    On the other hand django-tables2 (by design) has the name record for the current data in the row when you're customizing row attributes.

    You can read in the docs:

    By default, class names odd and even are supplied to the rows, which can be customized using the row_attrs Table.Meta attribute or as argument to the constructor of Table. String-like values will just be added, callables will be called with optional keyword argument record, the return value will be added. For example.