API Reference

Accessor (A)

class django_tables2.utils.Accessor(value)[source]

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.

To support list-of-dicts from QuerySet.values(), if the context is a dictionary, and the accessor is a key in the dictionary, it is returned right away.

RequestConfig

class django_tables2.config.RequestConfig(request, paginate=True)[source]

A configurator that uses request data to setup a table.

A single RequestConfig can be used for multiple tables in one view.

Parameters

paginate (dict or bool) –

Indicates whether to paginate, and if so, what default values to use. If the value evaluates to False, pagination will be disabled. A dict can be used to specify default values for the call to paginate (e.g. to define a default per_page value).

A special silent item can be used to enable automatic handling of pagination exceptions using the following logic:

For example, to use LazyPaginator:

RequestConfig(paginate={"paginator_class": LazyPaginator}).configure(table)

Table

class django_tables2.tables.Table(data=None, order_by=None, orderable=None, empty_text=None, exclude=None, attrs=None, row_attrs=None, pinned_row_attrs=None, sequence=None, prefix=None, order_by_field=None, page_field=None, per_page_field=None, template_name=None, default=None, request=None, show_header=None, show_footer=True, extra_columns=None)[source]

A representation of a table.

Parameters
  • data (QuerySet, list of dicts) – The data to display. This is a required variable, a TypeError will be raised if it’s not passed.

  • order_by – (tuple or str): The default ordering tuple or comma separated str. A hyphen - can be used to prefix a column name to indicate descending order, for example: ("name", "-age") or name,-age.

  • orderable (bool) – Enable/disable column ordering on this table

  • empty_text (str) – Empty text to render when the table has no data. (default Table.Meta.empty_text)

  • exclude (iterable or str) – The names of columns that should not be included in the table.

  • attrs (dict) – HTML attributes to add to the <table> tag. When accessing the attribute, the value is always returned as an AttributeDict to allow easily conversion to HTML.

  • row_attrs (dict) – Add custom html attributes to the table rows. Allows custom HTML attributes to be specified which will be added to the <tr> tag of the rendered table.

  • pinned_row_attrs (dict) – Same as row_attrs but for pinned rows.

  • sequence (iterable) –

    The sequence/order of columns the columns (from left to right).

    Items in the sequence must be column names, or "..." (string containing three periods). '...' can be used as a catch-all for columns that are not specified.

  • prefix (str) – A prefix for query string fields. To avoid name-clashes when using multiple tables on single page.

  • order_by_field (str) – If not None, defines the name of the order by query string field in the URL.

  • page_field (str) – If not None, defines the name of the current page query string field.

  • per_page_field (str) – If not None, defines the name of the per page query string field.

  • template_name (str) – The template to render when using {% render_table %} (defaults to DJANGO_TABLES2_TEMPLATE, which is "django_tables2/table.html" by default).

  • default (str) – Text to render in empty cells (determined by Column.empty_values, default Table.Meta.default)

  • request – Django’s request to avoid using RequestConfig

  • show_header (bool) – If False, the table will not have a header (<thead>), defaults to True

  • show_footer (bool) – If False, the table footer will not be rendered, even if some columns have a footer, defaults to True.

  • extra_columns (str, Column) – list of (name, column)-tuples containing extra columns to add to the instance. If column is None, the column with name will be removed from the table.

as_html(request)[source]

Render the table to an HTML table, adding request to the context.

as_values(exclude_columns=None)[source]

Return a row iterator of the data which would be shown in the table where the first row is the table headers.

Parameters

exclude_columns (iterable) – columns to exclude in the data iterator.

This can be used to output the table data as CSV, excel, for example using the ExportMixin.

If a column is defined using a Table.render_foo methods, the returned value from that method is used. If you want to differentiate between the rendered cell and a value, use a value_Foo-method:

class Table(tables.Table):
    name = tables.Column()

    def render_name(self, value):
        return format_html('<span class="name">{}</span>', value)

    def value_name(self, value):
        return value

will have a value wrapped in <span> in the rendered HTML, and just returns the value when as_values() is called.

Note that any invisible columns will be part of the row iterator.

before_render(request)[source]

A way to hook into the moment just before rendering the template.

Can be used to hide a column.

Parameters

request – contains the WGSIRequest instance, containing a user attribute if django.contrib.auth.middleware.AuthenticationMiddleware is added to your MIDDLEWARE_CLASSES.

Example:

class Table(tables.Table):
    name = tables.Column(orderable=False)
    country = tables.Column(orderable=False)

    def before_render(self, request):
        if request.user.has_perm('foo.delete_bar'):
            self.columns.hide('country')
        else:
            self.columns.show('country')
get_bottom_pinned_data()[source]

Return data for bottom pinned rows containing data for each row. Iterable type like: QuerySet, list of dicts, list of objects. Having a non-zero number of pinned rows will not result in an empty result set message being rendered, even if there are no regular data rows

Returns

None (default) no pinned rows at the bottom, iterable, data for pinned rows at the bottom.

Note

To show pinned row this method should be overridden.

Example

>>> class TableWithBottomPinnedRows(Table):
...     def get_bottom_pinned_data(self):
...         return [{
...             "column_a" : "some value",
...             "column_c" : "other value",
...         }]
get_column_class_names(classes_set, bound_column)[source]

Returns a set of HTML class names for cells (both td and th) of a bound column in this table. By default this returns the column class names defined in the table’s attributes. This method can be overridden to change the default behavior, for example to simply return classes_set.

Parameters
  • classes_set (set of string) – a set of class names to be added to the cell, retrieved from the column’s attributes. In the case of a header cell (th), this also includes ordering classes. To set the classes for a column, see Column. To configure ordering classes, see Changing class names for ordered column headers

  • bound_column (BoundColumn) – the bound column the class names are determined for. Useful for accessing bound_column.name.

Returns

A set of class names to be added to cells of this column

If you want to add the column names to the list of classes for a column, override this method in your custom table:

class MyTable(tables.Table):
    ...

    def get_column_class_names(self, classes_set, bound_column):
        classes_set = super().get_column_class_names(classes_set, bound_column)
        classes_set.add(bound_column.name)

        return classes_set
get_column_class_names(classes_set, bound_column)[source]

Returns a set of HTML class names for cells (both td and th) of a bound column in this table. By default this returns the column class names defined in the table’s attributes. This method can be overridden to change the default behavior, for example to simply return classes_set.

Parameters
  • classes_set (set of string) – a set of class names to be added to the cell, retrieved from the column’s attributes. In the case of a header cell (th), this also includes ordering classes. To set the classes for a column, see Column. To configure ordering classes, see Changing class names for ordered column headers

  • bound_column (BoundColumn) – the bound column the class names are determined for. Useful for accessing bound_column.name.

Returns

A set of class names to be added to cells of this column

If you want to add the column names to the list of classes for a column, override this method in your custom table:

class MyTable(tables.Table):
    ...

    def get_column_class_names(self, classes_set, bound_column):
        classes_set = super().get_column_class_names(classes_set, bound_column)
        classes_set.add(bound_column.name)

        return classes_set
get_top_pinned_data()[source]

Return data for top pinned rows containing data for each row. Iterable type like: QuerySet, list of dicts, list of objects. Having a non-zero number of pinned rows will not result in an empty result set message being rendered, even if there are no regular data rows

Returns

None (default) no pinned rows at the top, iterable, data for pinned rows at the top.

Note

To show pinned row this method should be overridden.

Example

>>> class TableWithTopPinnedRows(Table):
...     def get_top_pinned_data(self):
...         return [{
...             "column_a" : "some value",
...             "column_c" : "other value",
...         }]
paginate(paginator_class=<class 'django.core.paginator.Paginator'>, per_page=None, page=1, *args, **kwargs)[source]

Paginates the table using a paginator and creates a page property containing information for the current page.

Parameters
  • paginator_class (Paginator) – A paginator class to paginate the results.

  • per_page (int) – Number of records to display on each page.

  • page (int) – Page to display.

Extra arguments are passed to the paginator.

Pagination exceptions (EmptyPage and PageNotAnInteger) may be raised from this method and should be handled by the caller.

Table.Meta

class Table.Meta

Provides a way to define global settings for table, as opposed to defining them for each instance.

For example, if you want to create a table of users with their primary key added as a data-id attribute on each <tr>, You can use the following:

class UsersTable(tables.Table):
    class Meta:
        row_attrs = {"data-id": lambda record: record.pk}

Which adds the desired row_attrs to every instance of UsersTable, in contrast of defining it at construction time:

table = tables.Table(User.objects.all(),
                     row_attrs={"data-id": lambda record: record.pk})

Some settings are only available in Table.Meta and not as an argument to the Table constructor.

Note

If you define a class Meta on a child of a table already having a class Meta defined, you need to specify the parent’s Meta class as the parent for the class Meta in the child:

class PersonTable(table.Table):
    class Meta:
        model = Person
        exclude = ("email", )

class PersonWithEmailTable(PersonTable):
    class Meta(PersonTable.Meta):
        exclude = ()

All attributes are overwritten if defined in the child’s class Meta, no merging is attempted.

Arguments:
attrs (dict): Add custom HTML attributes to the table.

Allows custom HTML attributes to be specified which will be added to the <table> tag of any table rendered via Table.as_html() or the render_table template tag.

This is typically used to enable a theme for a table (which is done by adding a CSS class to the <table> element):

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

    class Meta:
        attrs = {"class": "paleblue"}

If you supply a a callable as a value in the dict, it will be called at table instantiation and the returned value will be used:

Consider this example where each table gets an unique "id" attribute:

import itertools
counter = itertools.count()

class UniqueIdTable(tables.Table):
    name = tables.Column()

    class Meta:
        attrs = {"id": lambda: "table_{}".format(next(counter))}

Note

This functionality is also available via the attrs keyword argument to a table’s constructor.

row_attrs (dict): Add custom html attributes to the table rows.

Allows custom HTML attributes to be specified which will be added to the <tr> tag of the rendered table. Optional keyword arguments are table and record.

This can be used to add each record’s primary key to each row:

class PersonTable(tables.Table):
    class Meta:
        model = Person
        row_attrs = {"data-id": lambda record: record.pk}

# will result in
'<tr data-id="1">...</tr>'

Note

This functionality is also available via the row_attrs keyword argument to a table’s constructor.

empty_text (str): Defines the text to display when the table has no rows.

If the table is empty and bool(empty_text) is True, a row is displayed containing empty_text. This is allows a message such as There are currently no FOO. to be displayed.

Note

This functionality is also available via the empty_text keyword argument to a table’s constructor.

show_header (bool): Whether or not to show the table header.

Defines whether the table header should be displayed or not, by default, the header shows the column names.

Note

This functionality is also available via the show_header keyword argument to a table’s constructor.

exclude (tuple): Exclude columns from the table.

This is useful in subclasses to exclude columns in a parent:

>>> class Person(tables.Table):
...     first_name = tables.Column()
...     last_name = tables.Column()
...
>>> Person.base_columns
{'first_name': <django_tables2.columns.Column object at 0x10046df10>,
'last_name': <django_tables2.columns.Column object at 0x10046d8d0>}
>>> class ForgetfulPerson(Person):
...     class Meta:
...         exclude = ("last_name", )
...
>>> ForgetfulPerson.base_columns
{'first_name': <django_tables2.columns.Column object at 0x10046df10>}

Note

This functionality is also available via the exclude keyword argument to a table’s constructor.

However, unlike some of the other Table.Meta options, providing the exclude keyword to a table’s constructor won’t override the Meta.exclude. Instead, it will be effectively be added to it. i.e. you can’t use the constructor’s exclude argument to undo an exclusion.

fields (tuple): Fields to show in the table.

Used in conjunction with model, specifies which fields should have columns in the table. If None, all fields are used, otherwise only those named:

# models.py
class Person(models.Model):
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)

# tables.py
class PersonTable(tables.Table):
    class Meta:
        model = Person
        fields = ("first_name", )
model (django.core.db.models.Model): Create columns from model.

A model to inspect and automatically create corresponding columns.

This option allows a Django model to be specified to cause the table to automatically generate columns that correspond to the fields in a model.

order_by (tuple or str): The default ordering tuple or comma separated str.

A hyphen - can be used to prefix a column name to indicate descending order, for example: ('name', '-age') or name,-age.

Note

This functionality is also available via the order_by keyword argument to a table’s constructor.

sequence (iterable): The sequence of the table columns.

This allows the default order of columns (the order they were defined in the Table) to be overridden.

The special item '...' can be used as a placeholder that will be replaced with all the columns that were not explicitly listed. This allows you to add columns to the front or back when using inheritance.

Example:

>>> class Person(tables.Table):
...     first_name = tables.Column()
...     last_name = tables.Column()
...
...     class Meta:
...         sequence = ("last_name", "...")
...
>>> Person.base_columns.keys()
['last_name', 'first_name']

The '...' item can be used at most once in the sequence value. If it is not used, every column must be explicitly included. For example in the above example, sequence = ('last_name', ) would be invalid because neither "..." or "first_name" were included.

Note

This functionality is also available via the sequence keyword argument to a table’s constructor.

orderable (bool): Default value for column’s orderable attribute.

If the table and column don’t specify a value, a column’s orderable value will fall back to this. This provides an easy mechanism to disable ordering on an entire table, without adding orderable=False to each column in a table.

Note

This functionality is also available via the orderable keyword argument to a table’s constructor.

template_name (str): The name of template to use when rendering the table.

Note

This functionality is also available via the template_name keyword argument to a table’s constructor.

localize (tuple): Specifies which fields should be localized in the

table. Read Controlling localization for more information.

unlocalize (tuple): Specifies which fields should be unlocalized in

the table. Read Controlling localization for more information.

Columns

Column

class django_tables2.columns.Column(verbose_name=None, accessor=None, default=None, visible=True, orderable=None, attrs=None, order_by=None, empty_values=None, localize=None, footer=None, exclude_from_export=False, linkify=False, initial_sort_descending=False)[source]

Represents a single column of a table.

Column objects control the way a column (including the cells that fall within it) are rendered.

Parameters
  • attrs (dict) –

    HTML attributes for elements that make up the column. This API is extended by subclasses to allow arbitrary HTML attributes to be added to the output.

    By default Column supports:

    • thtable/thead/tr/th elements

    • tdtable/tbody/tr/td elements

    • cell – fallback if th or td is not defined

    • a – To control the attributes for the a tag if the cell is wrapped in a link.

  • accessor (str or Accessor) – An accessor that describes how to extract values for this column from the table data.

  • default (str or callable) –

    The default value for the column. This can be a value or a callable object 1. If an object in the data provides None for a column, the default will be used instead.

    The default value may affect ordering, depending on the type of data the table is using. The only case where ordering is not affected is when a QuerySet is used as the table data (since sorting is performed by the database).

  • empty_values (iterable) – list of values considered as a missing value, for which the column will render the default value. Defaults to (None, '')

  • exclude_from_export (bool) – If True, this column will not be added to the data iterator returned from as_values().

  • footer (str, callable) – Defines the footer of this column. If a callable is passed, it can take optional keyword arguments column, bound_column and table.

  • order_by (str, tuple or Accessor) – Allows one or more accessors to be used for ordering rather than accessor.

  • orderable (bool) – If False, this column will not be allowed to influence row ordering/sorting.

  • verbose_name (str) – A human readable version of the column name.

  • visible (bool) – If True, this column will be rendered. Columns with visible=False will not be rendered, but will be included in .Table.as_values() and thus also in Exporting table data.

  • localize

    If the cells in this column will be localized by the localize filter:

    • If True, force localization

    • If False, values are not localized

    • If None (default), localization depends on the USE_L10N setting.

  • linkify (bool, str, callable, dict, tuple) –

    Controls if cell content will be wrapped in an a tag. The different ways to define the href attribute:

    • If True, the record.get_absolute_url() or the related model’s get_absolute_url() is used.

    • If a callable is passed, the returned value is used, if it’s not None. The callable can optionally accept any argument valid for Table.render_foo methods-methods, for example record or value.

    • If a dict is passed, it’s passed on to ~django.urls.reverse.

    • If a tuple is passed, it must be either a (viewname, args) or (viewname, kwargs) tuple, which is also passed to ~django.urls.reverse.

Examples, assuming this model:

class Blog(models.Model):
    title = models.CharField(max_length=100)
    body = model.TextField()
    user = model.ForeignKey(get_user_model(), on_delete=models.CASCADE)

Using the linkify argument to control the linkification. These columns will all display the value returned from str(record.user):

# If the column is named 'user', the column will use record.user.get_absolute_url()
user = tables.Column(linkify=True)

# We can also do that explicitly:
user = tables.Column(linkify=lambda record: record.user.get_absolute_url())

# or, if no get_absolute_url is defined, or a custom link is required, we have a couple
# of ways to define what is passed to reverse()
user = tables.Column(linkify={"viewname": "user_detail", "args": [tables.A("user__pk")]})
user = tables.Column(linkify=("user_detail", [tables.A("user__pk")])) # (viewname, args)
user = tables.Column(linkify=("user_detail", {"pk": tables.A("user__pk")})) # (viewname, kwargs)

initial_sort_descending (bool): If `True`, a column will sort in descending order
    on "first click" after table has been rendered. If `False`, column will follow
    default behavior, and sort ascending on "first click". Defaults to `False`.
1

The provided callable object must not expect to receive any arguments.

order(queryset, is_descending)[source]

Order the QuerySet of the table.

This method can be overridden by table.order_FOO() methods methods on the table or by subclassing Column; but only overrides if second element in return tuple is True.

Returns

Tuple (QuerySet, boolean)

render(value)[source]

Return the content for a specific cell.

This method can be overridden by Table.render_foo methods methods on the table or by subclassing Column.

If the value for this cell is in empty_values, this method is skipped and an appropriate default value is rendered instead. Subclasses should set empty_values to () if they want to handle all values in render.

value(**kwargs)[source]

Return the content for a specific cell for exports.

Similar to render but without any html content. This can be used to get the data in the formatted as it is presented but in a form that could be added to a csv file.

The default implementation just calls the render function but any subclasses where render returns html content should override this method.

See LinkColumn for an example.

BooleanColumn

class django_tables2.columns.BooleanColumn(null=False, yesno='✔,✘', **kwargs)[source]

A column suitable for rendering boolean data.

Parameters
  • null (bool) – is None different from False?

  • yesno (str) – comma separated values string or 2-tuple to display for True/False values.

Rendered values are wrapped in a <span> to allow customization by using CSS. By default the span is given the class true, false.

In addition to attrs keys supported by Column, the following are available:

  • span – adds attributes to the <span> tag

CheckBoxColumn

class django_tables2.columns.CheckBoxColumn(attrs=None, checked=None, **extra)[source]

A subclass of Column that renders as a checkbox form input.

This column allows a user to select a set of rows. The selection information can then be used to apply some operation (e.g. “delete”) onto the set of objects that correspond to the selected rows.

The value that is extracted from the table data for this column is used as the value for the checkbox, i.e. <input type="checkbox" value="..." />

This class implements some sensible defaults:

  • HTML input’s name attribute is the column name (can override via attrs argument).

  • orderable defaults to False.

Parameters
  • attrs (dict) –

    In addition to attrs keys supported by Column, the following are available:

    • input<input> elements in both <td> and <th>.

    • th__input – Replaces input attrs in header cells.

    • td__input – Replaces input attrs in body cells.

  • checked (Accessor, bool, callable) – Allow rendering the checkbox as checked. If it resolves to a truthy value, the checkbox will be rendered as checked.

Note

You might expect that you could select multiple checkboxes in the rendered table and then do something with that. This functionality is not implemented. If you want something to actually happen, you will need to implement that yourself.

property header

The value used for the column heading (e.g. inside the <th> tag).

By default this returns verbose_name.

Returns

unicode or None

Note

This property typically is not accessed directly when a table is rendered. Instead, BoundColumn.header is accessed which in turn accesses this property. This allows the header to fallback to the column name (it is only available on a BoundColumn object hence accessing that first) when this property doesn’t return something useful.

is_checked(value, record)[source]

Determine if the checkbox should be checked

render(value, bound_column, record)[source]

Return the content for a specific cell.

This method can be overridden by Table.render_foo methods methods on the table or by subclassing Column.

If the value for this cell is in empty_values, this method is skipped and an appropriate default value is rendered instead. Subclasses should set empty_values to () if they want to handle all values in render.

DateColumn

class django_tables2.columns.DateColumn(format=None, short=True, *args, **kwargs)[source]

A column that renders dates in the local timezone.

Parameters
  • format (str) – format string in same format as Django’s date template filter (optional)

  • short (bool) – if format is not specified, use Django’s SHORT_DATE_FORMAT setting, otherwise use DATE_FORMAT

classmethod from_field(field, **kwargs)[source]

Return a specialized column for the model field or None.

Parameters

field (Model Field instance) – the field that needs a suitable column

Returns

Column object or None

If the column is not specialized for the given model field, it should return None. This gives other columns the opportunity to do better.

If the column is specialized, it should return an instance of itself that is configured appropriately for the field.

DateTimeColumn

class django_tables2.columns.DateTimeColumn(format=None, short=True, *args, **kwargs)[source]

A column that renders datetime instances in the local timezone.

Parameters
  • format (str) – format string for datetime (optional). Note that format uses Django’s date template tag syntax.

  • short (bool) – if format is not specified, use Django’s SHORT_DATETIME_FORMAT, else DATETIME_FORMAT

classmethod from_field(field, **kwargs)[source]

Return a specialized column for the model field or None.

Parameters

field (Model Field instance) – the field that needs a suitable column

Returns

Column object or None

If the column is not specialized for the given model field, it should return None. This gives other columns the opportunity to do better.

If the column is specialized, it should return an instance of itself that is configured appropriately for the field.

EmailColumn

class django_tables2.columns.EmailColumn(text=None, *args, **kwargs)[source]

Render email addresses to mailto:-links.

Parameters
  • attrs (dict) – HTML attributes that are added to the rendered <a href="...">...</a> tag.

  • text – Either static text, or a callable. If set, this will be used to render the text inside link instead of the value.

Example:

# models.py
class Person(models.Model):
    name = models.CharField(max_length=200)
    email =  models.EmailField()

# tables.py
class PeopleTable(tables.Table):
    name = tables.Column()
    email = tables.EmailColumn()

# result
# [...]<a href="mailto:email@example.com">email@example.com</a>
classmethod from_field(field, **kwargs)[source]

Return a specialized column for the model field or None.

Parameters

field (Model Field instance) – the field that needs a suitable column

Returns

Column object or None

If the column is not specialized for the given model field, it should return None. This gives other columns the opportunity to do better.

If the column is specialized, it should return an instance of itself that is configured appropriately for the field.

FileColumn

class django_tables2.columns.FileColumn(verify_exists=True, **kwargs)[source]

Attempts to render FieldFile (or other storage backend File) as a hyperlink.

When the file is accessible via a URL, the file is rendered as a hyperlink. The basename is used as the text, wrapped in a span:

<a href="/media/path/to/receipt.pdf" title="path/to/receipt.pdf">receipt.pdf</a>

When unable to determine the URL, a span is used instead:

<span title="path/to/receipt.pdf" class>receipt.pdf</span>

Column.attrs keys a and span can be used to add additional attributes.

Parameters
  • verify_exists (bool) – attempt to determine if the file exists If verify_exists, the HTML class exists or missing is added to the element to indicate the integrity of the storage.

  • text (str or callable) – Either static text, or a callable. If set, this will be used to render the text inside the link instead of the file’s basename (default)

classmethod from_field(field, **kwargs)[source]

Return a specialized column for the model field or None.

Parameters

field (Model Field instance) – the field that needs a suitable column

Returns

Column object or None

If the column is not specialized for the given model field, it should return None. This gives other columns the opportunity to do better.

If the column is specialized, it should return an instance of itself that is configured appropriately for the field.

render(record, value)[source]

Return the content for a specific cell.

This method can be overridden by Table.render_foo methods methods on the table or by subclassing Column.

If the value for this cell is in empty_values, this method is skipped and an appropriate default value is rendered instead. Subclasses should set empty_values to () if they want to handle all values in render.

JSONColumn

class django_tables2.columns.JSONColumn(json_dumps_kwargs=None, **kwargs)[source]

Render the contents of JSONField or HStoreField as an indented string.

New in version 1.5.0.

Note

Automatic rendering of data to this column requires PostgreSQL support (psycopg2 installed) to import the fields, but this column can also be used manually without it.

Parameters
  • json_dumps_kwargs – kwargs passed to json.dumps, defaults to {'indent': 2}

  • attrs (dict) –

    In addition to attrs keys supported by Column, the following are available:

    • pre<pre> around the rendered JSON string in <td> elements.

classmethod from_field(field, **kwargs)[source]

Return a specialized column for the model field or None.

Parameters

field (Model Field instance) – the field that needs a suitable column

Returns

Column object or None

If the column is not specialized for the given model field, it should return None. This gives other columns the opportunity to do better.

If the column is specialized, it should return an instance of itself that is configured appropriately for the field.

render(record, value)[source]

Return the content for a specific cell.

This method can be overridden by Table.render_foo methods methods on the table or by subclassing Column.

If the value for this cell is in empty_values, this method is skipped and an appropriate default value is rendered instead. Subclasses should set empty_values to () if they want to handle all values in render.

LinkColumn

class django_tables2.columns.LinkColumn(viewname=None, urlconf=None, args=None, kwargs=None, current_app=None, attrs=None, **extra)[source]

Renders a normal value as an internal hyperlink to another page.

Note

This column should not be used anymore, the linkify keyword argument to regular columns can be used to achieve the same results.

It’s common to have the primary value in a row hyperlinked to the page dedicated to that record.

The first arguments are identical to that of reverse and allows an internal URL to be described. If this argument is None, then get_absolute_url. (see Django references) will be used. The last argument attrs allows custom HTML attributes to be added to the rendered <a href="..."> tag.

Parameters
  • viewname (str or None) – See reverse, or use None to use the model’s get_absolute_url

  • urlconf (str) – See reverse.

  • args (list) – See reverse. 2

  • kwargs (dict) – See reverse. 2

  • current_app (str) – See reverse.

  • attrs (dict) – HTML attributes that are added to the rendered <a ...>...</a> tag.

  • text (str or callable) – Either static text, or a callable. If set, this will be used to render the text inside link instead of value (default). The callable gets the record being rendered as argument.

2(1,2)

In order to create a link to a URL that relies on information in the current row, Accessor objects can be used in the args or kwargs arguments. The accessor will be resolved using the row’s record before reverse is called.

Example:

# models.py
class Person(models.Model):
    name = models.CharField(max_length=200)

# urls.py
urlpatterns = patterns('',
    url("people/([0-9]+)/", views.people_detail, name="people_detail")
)

# tables.py
from django_tables2.utils import A  # alias for Accessor

class PeopleTable(tables.Table):
    name = tables.LinkColumn("people_detail", args=[A("pk")])

In order to override the text value (i.e. <a ... >text</a>) consider the following example:

# tables.py
from django_tables2.utils import A  # alias for Accessor

class PeopleTable(tables.Table):
    name = tables.LinkColumn("people_detail", text="static text", args=[A("pk")])
    age  = tables.LinkColumn("people_detail", text=lambda record: record.name, args=[A("pk")])

In the first example, a static text would be rendered ("static text") In the second example, you can specify a callable which accepts a record object (and thus can return anything from it)

In addition to attrs keys supported by Column, the following are available:

  • a<a> elements in <td>.

Adding attributes to the <a>-tag looks like this:

class PeopleTable(tables.Table):
    first_name = tables.LinkColumn(attrs={
        "a": {"style": "color: red;"}
    })

ManyToManyColumn

class django_tables2.columns.ManyToManyColumn(transform=None, filter=None, separator=', ', linkify_item=None, *args, **kwargs)[source]

Display the list of objects from a ManyRelatedManager

Ordering is disabled for this column.

Parameters
  • transform – callable to transform each item to text, it gets an item as argument and must return a string-like representation of the item. By default, it calls force_str on each item.

  • filter – callable to filter, limit or order the QuerySet, it gets the ManyRelatedManager as first argument and must return a filtered QuerySet. By default, it returns all()

  • separator – separator string to join the items with. default: ", "

  • linkify_item – callable, arguments to reverse() or True to wrap items in a <a> tag. For a detailed explanation, see linkify argument to Column.

For example, when displaying a list of friends with their full name:

# models.py
class Person(models.Model):
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    friends = models.ManyToManyField(Person)
    is_active = models.BooleanField(default=True)

    @property
    def name(self):
        return '{} {}'.format(self.first_name, self.last_name)

# tables.py
class PersonTable(tables.Table):
    name = tables.Column(order_by=("last_name", "first_name"))
    friends = tables.ManyToManyColumn(transform=lambda user: u.name)

If only the active friends should be displayed, you can use the filter argument:

friends = tables.ManyToManyColumn(filter=lambda qs: qs.filter(is_active=True))
filter(qs)[source]

Filter is called on the ManyRelatedManager to allow ordering, filtering or limiting on the set of related objects.

classmethod from_field(field, **kwargs)[source]

Return a specialized column for the model field or None.

Parameters

field (Model Field instance) – the field that needs a suitable column

Returns

Column object or None

If the column is not specialized for the given model field, it should return None. This gives other columns the opportunity to do better.

If the column is specialized, it should return an instance of itself that is configured appropriately for the field.

render(value)[source]

Return the content for a specific cell.

This method can be overridden by Table.render_foo methods methods on the table or by subclassing Column.

If the value for this cell is in empty_values, this method is skipped and an appropriate default value is rendered instead. Subclasses should set empty_values to () if they want to handle all values in render.

transform(obj)[source]

Transform is applied to each item of the list of objects from the ManyToMany relation.

RelatedLinkColumn

class django_tables2.columns.RelatedLinkColumn(viewname=None, urlconf=None, args=None, kwargs=None, current_app=None, attrs=None, **extra)[source]

Render a link to a related object using related object’s get_absolute_url, same parameters as ~.LinkColumn.

Note

This column should not be used anymore, the linkify keyword argument to regular columns can be used achieve the same results.

If the related object does not have a method called get_absolute_url, or if it is not callable, the link will be rendered as ‘#’.

Traversing relations is also supported, suppose a Person has a foreign key to Country which in turn has a foreign key to Continent:

class PersonTable(tables.Table):
    name = tables.Column()
    country = tables.RelatedLinkColumn()
    continent = tables.RelatedLinkColumn(accessor="country.continent")

will render:

  • in column ‘country’, link to person.country.get_absolute_url() with the output of str(person.country) as <a> contents.

  • in column ‘continent’, a link to person.country.continent.get_absolute_url() with the output of str(person.country.continent) as <a> contents.

Alternative contents of <a> can be supplied using the text keyword argument as documented for LinkColumn.

TemplateColumn

class django_tables2.columns.TemplateColumn(template_code=None, template_name=None, extra_context=None, **extra)[source]

A subclass of Column that renders some template code to use as the cell value.

Parameters
  • template_code (str) – template code to render

  • template_name (str) – name of the template to render

  • extra_context (dict) – optional extra template context

A Template object is created from the template_code or template_name and rendered with a context containing:

  • record – data record for the current row

  • value – value from record that corresponds to the current column

  • default – appropriate default value to use as fallback.

  • row_counter – The number of the row this cell is being rendered in.

  • any context variables passed using the extra_context argument to TemplateColumn.

Example:

class ExampleTable(tables.Table):
    foo = tables.TemplateColumn("{{ record.bar }}")
    # contents of `myapp/bar_column.html` is `{{ label }}: {{ value }}`
    bar = tables.TemplateColumn(template_name="myapp/name2_column.html",
                                extra_context={"label": "Label"})

Both columns will have the same output.

render(record, table, value, bound_column, **kwargs)[source]

Return the content for a specific cell.

This method can be overridden by Table.render_foo methods methods on the table or by subclassing Column.

If the value for this cell is in empty_values, this method is skipped and an appropriate default value is rendered instead. Subclasses should set empty_values to () if they want to handle all values in render.

value(**kwargs)[source]

The value returned from a call to value() on a TemplateColumn is the rendered template with django.utils.html.strip_tags applied. Leading and trailing whitespace is stripped.

URLColumn

class django_tables2.columns.URLColumn(text=None, *args, **kwargs)[source]

Renders URL values as hyperlinks.

Parameters
  • text (str or callable) – Either static text, or a callable. If set, this will be used to render the text inside link instead of value (default)

  • attrs (dict) – Additional attributes for the <a> tag

Example:

>>> class CompaniesTable(tables.Table):
...     link = tables.URLColumn()
...
>>> table = CompaniesTable([{"link": "http://google.com"}])
>>> table.rows[0].get_cell("link")
'<a href="http://google.com">http://google.com</a>'
classmethod from_field(field, **kwargs)[source]

Return a specialized column for the model field or None.

Parameters

field (Model Field instance) – the field that needs a suitable column

Returns

Column object or None

If the column is not specialized for the given model field, it should return None. This gives other columns the opportunity to do better.

If the column is specialized, it should return an instance of itself that is configured appropriately for the field.

Views, view mixins and paginators

SingleTableMixin

class django_tables2.views.SingleTableMixin[source]

Adds a Table object to the context. Typically used with TemplateResponseMixin.

table_class

subclass of Table

table_data

data used to populate the table, any compatible data source.

context_table_name

name of the table’s template variable (default: ‘table’)

Type

str

table_pagination

controls table pagination. If a dict, passed as the paginate keyword argument to RequestConfig. As such, any Truthy value enables pagination. (default: enable pagination).

The dict can be used to specify values for arguments for the call to paginate.

If you want to use a non-standard paginator for example, you can add a key paginator_class to the dict, containing a custom Paginator class.

Type

dict

This mixin plays nice with the Django’s .MultipleObjectMixin by using .get_queryset as a fall back for the table data source.

get_context_data(**kwargs)[source]

Overridden version of TemplateResponseMixin to inject the table into the template’s context.

get_table(**kwargs)[source]

Return a table object to use. The table has automatic support for sorting and pagination.

get_table_class()[source]

Return the class to use for the table.

get_table_data()[source]

Return the table data that should be used to populate the rows.

get_table_kwargs()[source]

Return the keyword arguments for instantiating the table.

Allows passing customized arguments to the table constructor, for example, to remove the buttons column, you could define this method in your View:

def get_table_kwargs(self):
    return {
        'exclude': ('buttons', )
    }

MultiTableMixin

class django_tables2.views.MultiTableMixin[source]

Add a list with multiple Table object’s to the context. Typically used with TemplateResponseMixin.

The tables attribute must be either a list of Table instances or classes extended from Table which are not already instantiated. In that case, get_tables_data must be able to return the tables data, either by having an entry containing the data for each table in tables, or by overriding this method in order to return this data.

tables

list of Table instances or list of Table child objects.

tables_data

if defined, tables is assumed to be a list of table classes which will be instantiated with the corresponding item from this list of TableData instances.

table_prefix

Prefix to be used for each table. The string must contain one instance of {}, which will be replaced by an integer different for each table in the view. Default is ‘table_{}-‘.

Type

str

context_table_name

name of the table’s template variable (default: ‘tables’)

Type

str

New in version 1.2.3.

get_tables()[source]

Return an array of table instances containing data.

get_tables_data()[source]

Return an array of table_data that should be used to populate each table

SingleTableView

class django_tables2.views.SingleTableView(**kwargs)[source]

Generic view that renders a template and passes in a Table instances.

Mixes .SingleTableMixin with django.views.generic.list.ListView.

get_table(**kwargs)

Return a table object to use. The table has automatic support for sorting and pagination.

get_table_kwargs()

Return the keyword arguments for instantiating the table.

Allows passing customized arguments to the table constructor, for example, to remove the buttons column, you could define this method in your View:

def get_table_kwargs(self):
    return {
        'exclude': ('buttons', )
    }

export.TableExport

class django_tables2.export.TableExport(export_format, table, exclude_columns=None, dataset_kwargs=None)[source]

Export data from a table to the file type specified.

Parameters
  • export_format (str) – one of csv, json, latex, ods, tsv, xls, xlsx, yaml

  • table (Table) – instance of the table to export the data from

  • exclude_columns (iterable) – list of column names to exclude from the export

  • dataset_kwargs (dictionary) – passed as **kwargs to tablib.Dataset constructor

content_type()[source]

Returns the content type for the current export format

export()[source]

Returns the string/bytes for the current export format

classmethod is_valid_format(export_format)[source]

Returns true if export_format is one of the supported export formats

response(filename=None)[source]

Builds and returns a HttpResponse containing the exported data

Parameters

filename (str) – if not None, the filename is attached to the Content-Disposition header of the response.

table_to_dataset(table, exclude_columns, dataset_kwargs=None)[source]

Transform a table to a tablib dataset.

export.ExportMixin

class django_tables2.export.ExportMixin[source]

Support various export formats for the table data.

ExportMixin looks for some attributes on the class to change it’s behavior:

export_class

Allows using a custom implementation of TableExport.

Type

TableExport

export_name

is the name of file that will be exported, without extension.

Type

str

export_trigger_param

is the name of the GET attribute used to trigger the export. It’s value decides the export format, refer to TableExport for a list of available formats.

Type

str

exclude_columns

column names excluded from the export. For example, one might want to exclude columns containing buttons from the export. Excluding columns from the export is also possible using the exclude_from_export argument to the Column constructor:

class Table(tables.Table):
    name = tables.Column()
    buttons = tables.TemplateColumn(exclude_from_export=True, template_name=...)
Type

iterable

export_formats

export formats to render a set of buttons in the template.

Type

iterable

dataset_kwargs

passed as **kwargs to tablib.Dataset constructor:

dataset_kwargs = {"tite": "My custom tab title"}
Type

dictionary

export_class

alias of django_tables2.export.export.TableExport

LazyPaginator

class django_tables2.paginators.LazyPaginator(object_list, per_page, look_ahead=None, **kwargs)[source]

Implement lazy pagination, preventing any count() queries.

By default, for any valid page, the total number of pages for the paginator will be

  • current + 1 if the number of records fetched for the current page offset is bigger than the number of records per page.

  • current if the number of records fetched is less than the number of records per page.

The number of additional records fetched can be adjusted using look_ahead, which defaults to 1 page. If you like to provide a little more extra information on how much pages follow the current page, you can use a higher value.

Note

The number of records fetched for each page is per_page * look_ahead + 1, so increasing the value for look_ahead makes the view a bit more expensive.

So:

paginator = LazyPaginator(range(10000), 10)

>>> paginator.page(1).object_list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> paginator.num_pages
2
>>> paginator.page(10).object_list
[91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
>>> paginator.num_pages
11
>>> paginator.page(1000).object_list
[9991, 9992, 9993, 9994, 9995, 9996, 9997, 9998, 9999]
>>> paginator.num_pages
1000

Usage with SingleTableView:

class UserListView(SingleTableView):
    table_class = UserTable
    table_data = User.objects.all()
    pagination_class = LazyPaginator

Or with RequestConfig:

RequestConfig(paginate={"paginator_class": LazyPaginator}).configure(table)

New in version 2.0.0.

See Internal APIs for internal classes.