API Reference¶
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. See [pagination]
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. Adict
can be used to specify default values for the call topaginate
(e.g. to define a defaultper_page
value).A special silent item can be used to enable automatic handling of pagination exceptions using the following logic:
- If
PageNotAnInteger
is raised, show the first page. - If
EmptyPage
is raised, show the last page.
- If
Table
¶
-
class
django_tables2.tables.
Table
(data, order_by=None, orderable=None, empty_text=None, exclude=None, attrs=None, row_attrs=None, sequence=None, prefix=None, order_by_field=None, page_field=None, per_page_field=None, template=None, default=None, request=None, show_header=None, show_footer=True)¶ A representation of a table.
Parameters: - data (queryset, list of dicts) – The data to display.
- 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')
orname,-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 shouldn’t 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 anAttributeDict
to allow easily conversion to HTML. - row_attrs – 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. - 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 aren’t specified. - prefix (str) – A prefix for querystring 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 querystring field in the url. - page_field (str) – If not
None
, defines the name of the current page querystring field. - per_page_field (str) – If not
None
, defines the name of the per page querystring field. - template (str) – The template to render when using
{% render_table %}
(default'django_tables2/table.html'
) - default (str) – Text to render in empty cells (determined by
Column.empty_values
, defaultTable.Meta.default
) - request – Django’s request to avoid using
RequestConfig
- show_header (bool) – If
False
, the table will not have a header (<thead>
), defaults toTrue
- show_footer (bool) – If
False
, the table footer will not be rendered, even if some columns have a footer, defaults toTrue
.
-
as_html
(request)¶ Render the table to an HTML table, adding
request
to the context.
-
get_column_class_names
(classes_set, bound_column)¶ 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, and additionally the bound column’s name. 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 accessingbound_column.name
.
Returns: A set of class names to be added to cells of this column
- 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
-
paginate
(klass=<class 'django.core.paginator.Paginator'>, per_page=None, page=1, *args, **kwargs)¶ Paginates the table using a paginator and creates a
page
property containing information for the current page.Parameters: Extra arguments are passed to the paginator.
Pagination exceptions (
EmptyPage
andPageNotAnInteger
) 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 ofUsersTable
, 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 theTable
constructor.Note
If you define a
class Meta
on a child of a table already having aclass Meta
defined, you need to specify the parent’sMeta
class as the parent for theclass 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 viaTable.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 instatiation an de returned value will be used:
Consider this example where each table gets an unieque
"id"
attribute:import itertools counter = itertools.count() class UniqueIdTable(tables.Table): name = tables.Column() class Meta: attrs = {'id': lambda: 'table_%d' % 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.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>'
New in version 1.2.0.
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)
isTrue
, a row is displayed containingempty_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): Wether 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 (typle or str): 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 theexclude
keyword to a table’s constructor won’t override theMeta.exclude
. Instead, it will be effectively be added to it. i.e. you can’t use the constructor’sexclude
argument to undo an exclusion.
- attrs (
- fields (
tuple
orstr
): Fields to show in the table. Used in conjunction with
model
, specifies which fields should have columns in the table. IfNone
, 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')
orname,-age
.Note
This functionality is also available via the
order_by
keyword argument to a table’s constructor.- sequence (iteralbe): 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 weren’t 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’s not used, every column must be explicitly included. e.g. 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 fallback to this. This provides an easy mechanism to disable ordering on an entire table, without addingorderable=False
to each column in a table.Note
This functionality is also available via the
orderable
keyword argument to a table’s constructor.
template (str): The default template to use when rendering the table.
Note
This functionality is also available via the template keyword argument to a table’s constructor.
- localize (str or tuple): Specifies which fields should be localized in the
- table. Read Controlling localization for more information.
- unlocalize (str or tuple): Specifies which fields should be unlocalized in
- the table. Read Controlling localization for more information.
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)[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:- th –
table/thead/tr/th
elements - td –
table/tbody/tr/td
elements - cell – fallback if th or td isn’t defined
- th –
- 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). - 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. - localize –
If the cells in this column will be localized by the
localize
filter:
[1] The provided callable object must not expect to receive any arguments. - attrs (dict) –
BooleanColumn
¶
-
class
django_tables2.columns.
BooleanColumn
(null=False, yesno=u'u2714, u2718', **kwargs)[source]¶ A column suitable for rendering boolean data.
Parameters: Rendered values are wrapped in a
<span>
to allow customisation by themes. By default the span is given the classtrue
,false
.In addition to attrs keys supported by
Column
, the following are available:- span – adds attributes to the
<span>
tag
- span – adds attributes to the
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.
- input –
- 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.
- HTML input’s
DateColumn
¶
DateTimeColumn
¶
EmailColumn
¶
-
class
django_tables2.columns.
EmailColumn
(attrs=None, 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>
- attrs (dict) – HTML attributes that are added to the rendered
FileColumn
¶
-
class
django_tables2.columns.
FileColumn
(verify_exists=True, **kwargs)[source]¶ Attempts to render
FieldFile
(or other storage backendFile
) 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:<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">receipt.pdf</span>
Column.attrs
keysa
andspan
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
ormissing
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)
- verify_exists (bool) – attempt to determine if the file exists
If verify_exists, the HTML class
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.
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 isNone
, thenget_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) – See
reverse
, or useNone
to use the model’sget_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 beforereverse
is called.Example:
# models.py class Person(models.Model): name = models.CharField(max_length=200) # urls.py urlpatterns = patterns('', url('people/(\d+)/', 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;'} })
- viewname (str) – See
TemplateColumn
¶
-
class
django_tables2.columns.
TemplateColumn
(template_code=None, template_name=None, **extra)[source]¶ A subclass of
Column
that renders some template code to use as the cell value.Parameters: 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
Example:
class ExampleTable(tables.Table): foo = tables.TemplateColumn('{{ record.bar }}') # contents of `myapp/bar_column.html` is `{{ value }}` bar = tables.TemplateColumn(template_name='myapp/name2_column.html')
Both columns will have the same output.
URLColumn
¶
-
class
django_tables2.columns.
URLColumn
(attrs=None, 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): ... www = tables.URLColumn() ... >>> table = CompaniesTable([{'www': 'http://google.com'}]) >>> table.rows[0].get_cell('www') '<a href="http://google.com">http://google.com</a>'
SingleTableMixin
¶
-
class
django_tables2.views.
SingleTableMixin
[source]¶ Adds a Table object to the context. Typically used with
TemplateResponseMixin
.-
table_data
¶ data used to populate the table, any compatible data source.
-
context_table_name
¶ str – name of the table’s template variable (default: ‘table’)
-
table_pagination
¶ dict – controls table pagination. If a
dict
, passed as the paginate keyword argument toRequestConfig
. As such, any Truthy value enables pagination. (default: enable pagination)
This mixin plays nice with the Django’s`.MultipleObjectMixin` by using
get_queryset`
as a fallback for the table data source.-
get_context_data
(**kwargs)[source]¶ Overriden version of
TemplateResponseMixin
to inject the table into the template’s context.
-
MultiTableMixin
¶
-
class
django_tables2.views.
MultiTableMixin
[source]¶ Adds a Table object to the context. Typically used with
TemplateResponseMixin
.the
tables
attribute must be either a list ofTable
instances or classes extended fromTable
which are not already instantiated. In that case, tables_data must be defined, having an entry containing the data for each table intables
.-
tables_data
¶ if defined,
tables
is assumed to be a list of table classes which will be instatiated with the corresponding item from this list ofTableData
instances.
-
table_prefix
¶ str – 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_{}-‘.
-
context_table_name
¶ str – name of the table’s template variable (default: ‘tables’)
New in version 1.2.3.
-
See Internal APIs for internal classes.