Internal APIs

The items documented here are internal and subject to change.


class django_tables2.columns.BoundColumns(table)

Container for spawning BoundColumn objects.

This is bound to a table and provides its Table.columns property. It provides access to those columns in different ways (iterator, item-based, filtered and unfiltered etc), stuff that would not be possible with a simple iterator in the table class.

A BoundColumns object is a container for holding BoundColumn objects. It provides methods that make accessing columns easier than if they were stored in a list or dict. Columns has a similar API to a dict (it actually uses a OrderedDict interally).

At the moment you’ll only come across this class when you access a Table.columns property.

Parameters:table (Table) – the table containing the columns

Check if a column is contained within a Columns object.

item can either be a BoundColumn object, or the name of a column.


Retrieve a specific BoundColumn object.

index can either be 0-indexed or the name of a column

columns['speed']  # returns a bound column with name 'speed'
columns[0]        # returns the first column

Convenience API, alias of itervisible.


Return how many BoundColumn objects are contained (and visible).


list of weak references to the object (if defined)


Return an iterator that exposes all BoundColumn objects, regardless of visiblity or sortability.


Return an iterator of (name, column) pairs (where column is a BoundColumn).

This method is the mechanism for retrieving columns that takes into consideration all of the ordering and filtering modifiers that a table supports (e.g. exclude and sequence).


Same as BoundColumns.all but only returns orderable columns.

This is useful in templates, where iterating over the full set and checking {% if column.ordarable %} can be problematic in conjunction with e.g. {{ forloop.last }} (the last column might not be the actual last that is rendered).


Same as iterorderable but only returns visible BoundColumn objects.

This is geared towards table rendering.


class django_tables2.columns.BoundColumn(table, column, name)

A run-time version of Column. The difference between BoundColumn and Column, is that BoundColumn objects include the relationship between a Column and a Table. In practice, this means that a BoundColumn knows the “variable name” given to the Column when it was declared on the Table.

For convenience, all Column properties are available from this class.

  • table (Table) – The table in which this column exists
  • column (Column) – The type of column
  • name (str) –

    The variable name of the column used when defining the Table. In this example the name is age:

    class SimpleTable(tables.Table):
        age = tables.Column()

list of weak references to the object (if defined)


Returns the string used to access data for this column out of the data source.


Proxy to Column.attrs but injects some values of our own.

A th and td are guaranteed to be defined (irrespective of what’s actually defined in the column attrs. This makes writing templates easier.


Returns the default value for this column.


Returns the HTML class attribute for a data cell in this column


Returns the HTML class attribute for a header cell in this column


The value that should be used in the header cell for this column.


Returns True, False or None as described in Column.localize


Returns an OrderByTuple of appropriately prefixed data source keys used to sort this column.

See order_by_alias for details.


Returns an OrderBy describing the current state of ordering for this column.

The following attempts to explain the difference between order_by and order_by_alias.

order_by_alias returns and OrderBy instance that’s based on the name of the column, rather than the keys used to order the table data. Understanding the difference is essential.

Having an alias and a keys version is necessary because an N-tuple (of data source keys) can be used by the column to order the data, and it’s ambiguous when mapping from N-tuple to column (since multiple columns could use the same N-tuple).

The solution is to use order by aliases (which are really just prefixed column names) that describe the ordering state of the column, rather than the specific keys in the data source should be ordered.


>>> class SimpleTable(tables.Table):
...     name = tables.Column(order_by=('firstname', 'last_name'))
>>> table = SimpleTable([], order_by=('-name', ))
>>> table.columns['name'].order_by_alias
>>> table.columns['name'].order_by
('-first_name', '-last_name')

The OrderBy returned has been patched to include an extra attribute next, which returns a version of the alias that would be transitioned to if the user toggles sorting on this column, e.g.:

not sorted -> ascending
ascending  -> descending
descending -> ascending

This is useful otherwise in templates you’d need something like:

{% if column.is_ordered %}
{% querystring table.prefixed_order_by_field=column.order_by_alias.opposite %}
{% else %}
{% querystring table.prefixed_order_by_field=column.order_by_alias %}
{% endif %}

Return a bool depending on whether this column supports ordering.


Return the verbose name for this column.

In order of preference, this will return:
  1. The column’s explicitly defined verbose_name
  2. The titlised model’s verbose_name (if applicable)
  3. Fallback to the titlised column name.

Any verbose_name that was not passed explicitly in the column definition is returned titlised in keeping with the Django convention of verbose_name being defined in lowercase and uppercased/titlised as needed by the application.

If the table is using queryset data, then use the corresponding model field’s verbose_name. If it’s traversing a relationship, then get the last field in the accessor (i.e. stop when the relationship turns from ORM relationships to object attributes [e.g. person.upper should stop at person]).


Returns a bool depending on whether this column is visible.


class django_tables2.rows.BoundRows(data, table, pinned_data=None)

Container for spawning BoundRow objects.

  • data – iterable of records
  • table – the Table in which the rows exist
  • pinned_data – dictionary with iterable of records for top and/or bottom pinned rows.


>>> pinned_data = {
...    'top': iterable,      # or None value
...    'bottom': iterable,   # or None value
... }

This is used for rows.


Slicing returns a new BoundRows instance, indexing returns a single BoundRow instance.


list of weak references to the object (if defined)


Top and bottom pinned rows generator.

Parameters:data – Iterable datas for all records for top or bottom pinned rows.
Yields:BoundPinnedRow – Top or bottom BoundPinnedRow object for single pinned record.


class django_tables2.rows.BoundRow(record, table)

Represents a specific row in a table.

BoundRow objects are a container that make it easy to access the final ‘rendered’ values for cells in a row. You can simply iterate over a BoundRow object and it will take care to return values rendered using the correct method (e.g. Table.render_foo methods)

To access the rendered value of each cell in a row, just iterate over it:

>>> import django_tables2 as tables
>>> class SimpleTable(tables.Table):
...     a = tables.Column()
...     b = tables.CheckBoxColumn(attrs={'name': 'my_chkbox'})
>>> table = SimpleTable([{'a': 1, 'b': 2}])
>>> row = table.rows[0]  # we only have one row, so let's use it
>>> for cell in row:
...     print(cell)
<input type="checkbox" name="my_chkbox" value="2" />

Alternatively you can use row.get_cell() to retrieve a specific cell:

>>> row.get_cell(0)
>>> row.get_cell(1)
u'<input type="checkbox" name="my_chkbox" value="2" />'
>>> row.get_cell(2)
IndexError: list index out of range

Finally you can also use the column names to retrieve a specific cell:

>>> row.get_cell('a')
>>> row.get_cell('b')
u'<input type="checkbox" name="my_chkbox" value="2" />'
>>> row.get_cell('c')
KeyError: 'c'
  • table – The Table in which this row exists.
  • record – a single record from the table data that is used to populate the row. A record could be a Model object, a dict, or something else.

Check by both row object and column name.


Iterate over the rendered values for cells in the row.

Under the hood this method just makes a call to BoundRow.__getitem__ for each cell.


list of weak references to the object (if defined)

_call_render(bound_column, value=None)

Call the column’s render method with appropriate kwargs

_call_value(bound_column, value=None)

Call the column’s value method with appropriate kwargs


Return the attributes for a certain row.


Returns the final rendered html for a cell in the row, given the name of a column.


Returns the final rendered value (excluding any html) for a cell in the row, given the name of a column.


Return css class, alternating for odd and even records.

Returns:even for even records, odd otherwise.
Return type:string

Returns iterator yielding (bound_column, cell) pairs.

cell is row[name] – the rendered unicode value that should be rendered within ``<td>.


The data record from the data source which is used to populate this row with data.


The associated Table object.


class django_tables2.rows.BoundPinnedRow(record, table)

Represents a pinned row in a table. Inherited from BoundRow.

_get_and_render_with(name, render_func, default)

Get raw value from record for render in table. This value using by render_func.

  • name – String describing a path from one object to another.
  • render_func – Only for compatibility - not used.

Raw value from record for single cell.

Return type:



Return the attributes for a certain pinned row. Add css clases pinned-row to class attribute.

Returns:Attributes for pinned rows.
Return type:AttributeDict


class django_tables2.tables.TableData(data, table)

Base class for table data containers.


Slicing returns a new TableData instance, indexing returns a single record.


for ... in ... default to using this. There’s a bug in Django 1.3 with indexing into querysets, so this side-steps that problem (as well as just being a better way to iterate).


list of weak references to the object (if defined)


class django_tables2.utils.Sequence

Represents a column sequence, e.g. ('first_name', '...', 'last_name')

This is used to represent Table.Meta.sequence or the Table constructors’s sequence keyword argument.

The sequence must be a list of column names and is used to specify the order of the columns on a table. Optionally a ‘...’ item can be inserted, which is treated as a catch-all for column names that aren’t explicitly specified.


list of weak references to the object (if defined)


Expands the '...' item in the sequence into the appropriate column names that should be placed there.

Raises:ValueError if the sequence is invalid for the columns.
class django_tables2.utils.OrderBy

A single item in an OrderByTuple object. This class is essentially just a str with some extra properties.


ReturnsOrderBy – the bare form.

The bare form is the non-prefixed form. Typically the bare form is just the ascending form.

Example: age is the bare form of -age


Returns the current instance usable in Django QuerySet’s order_by arguments.


Returns True if this object induces ascending ordering.


Returns True if this object induces descending ordering.


Provides the opposite of the current sorting directon.

Returns:object with an opposite sort influence.
Return type:OrderBy


>>> order_by = OrderBy('name')
>>> order_by.opposite
class django_tables2.utils.OrderByTuple

Stores ordering as (as OrderBy objects). The order_by property is always converted to an OrderByTuple object.

This class is essentially just a tuple with some useful extras.


>>> x = OrderByTuple(('name', '-age'))
>>> x['age']
>>> x['age'].is_descending
>>> x['age'].opposite

Determine if a column has an influence on ordering.


>>> x = OrderByTuple(('name', ))
>>> 'name' in  x
>>> '-name' in x
Parameters:name (str) – The name of a column. (optionally prefixed)
Returns:True if the column with name influences the ordering.
Return type:bool

Allows an OrderBy object to be extracted via named or integer based indexing.

When using named based indexing, it’s fine to used a prefixed named:

>>> x = OrderByTuple(('name', '-age'))
>>> x[0]
>>> x['age']
>>> x['-age']
Parameters:index (int) – Index to query the ordering for.
Returns:for the ordering at the index.
Return type:OrderBy
get(key, fallback)

Identical to __getitem__, but supports fallback value.


Return version with each OrderBy prefix toggled:

>>> order_by = OrderByTuple(('name', '-age'))
>>> order_by.opposite
('-name', 'age')
class django_tables2.utils.Accessor

A string describing a path from one object to another via attribute/index accesses. For convenience, the class has an alias A to allow for more concise code.

Relations are separated by a . character.


Return the django model field for model in context, following relations.

penultimate(context, quiet=True)
Split the accessor on the right-most dot ‘.’, return a tuple with:
  • the resolved left part.
  • the remainder


>>> Accessor('a.b.c').penultimate({'a': {'a': 1, 'b': {'c': 2, 'd': 4}}})
({'c': 2, 'd': 4}, 'c')
resolve(context, safe=True, quiet=False)

Return an object described by the accessor by traversing the attributes of context.

Lookups are attempted in the following order:

  • dictionary (e.g. obj[related])
  • attribute (e.g. obj.related)
  • list-index lookup (e.g. obj[int(related)])

Callable objects are called, and their result is used, before proceeding with the resolving.


>>> x = Accessor('__len__')
>>> x.resolve('brad')
>>> x = Accessor('0.upper')
>>> x.resolve('brad')
  • context (object) – The root/first object to traverse.
  • safe (bool) – Don’t call anything with alters_data = True
  • quiet (bool) – Smother all exceptions and instead return None

target object

class django_tables2.utils.AttributeDict

A wrapper around dict that knows how to render itself as HTML style tag attributes.

The returned string is marked safe, so it can be used safely in a template. See as_html for a usage example.


list of weak references to the object (if defined)


Render to HTML tag attributes.


>>> from django_tables2.utils import AttributeDict
>>> attrs = AttributeDict({'class': 'mytable', 'id': 'someid'})
>>> attrs.as_html()
'class="mytable" id="someid"'
Return type:SafeUnicode object
Returns a (arguments, kwarg_name)-tuple:
  • the arguments (positional or keyword)
  • the name of the ** kwarg catch all.
Return type:tuple

The self-argument for methods is always removed.

django_tables2.utils.call_with_appropriate(fn, kwargs)

Calls the function fn with the keyword arguments from kwargs it expects

If the kwargs argument is defined, pass all arguments, else provide exactly the arguments wanted.

django_tables2.utils.computed_values(d, *args, **kwargs)

Returns a new dict that has callable values replaced with the return values.


>>> compute_values({'foo': lambda: 'bar'})
{'foo': 'bar'}

Arbitrarily deep structures are supported. The logic is as follows:

  1. If the value is callable, call it and make that the new value.
  2. If the value is an instance of dict, use ComputableDict to compute its keys.


>>> def parents():
...     return {
...         'father': lambda: 'Foo',
...         'mother': 'Bar'
...      }
>>> a = {
...     'name': 'Brad',
...     'parents': parents
... }
>>> computed_values(a)
{'name': 'Brad', 'parents': {'father': 'Foo', 'mother': 'Bar'}}
  • d (dict) – The original dictionary.
  • args – any extra positional arguments will be passed to the callables
  • kwargs – any extra keyword arguments will be passed to the callables.

with callable values replaced.

Return type: