API Reference¶
RequestConfig¶
-
class
django_tables2.config.RequestConfig(request, paginate=True)[source]¶ A configurator that uses request data to setup a table.
Parameters: paginate ( dictorbool) –indicates whether to paginate, and if so, what default values to use. If the value evaluates to
False, pagination will be disabled. Adictcan be used to specify default values for the call topaginate(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 algorithm:
- If
PageNotAnInteger`is raised, show the first page. - If
EmptyPageis 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, sequence=None, prefix=None, order_by_field=None, page_field=None, per_page_field=None, template=None, sortable=None, default=None, request=None)¶ -
as_html()¶ Render the table to a simple HTML table.
If this method is used in the request/response cycle, any links generated will clobber the querystring of the request. Use the
{% render_table %}template tag instead.
-
paginate(klass=<class 'django.core.paginator.Paginator'>, per_page=None, page=1, *args, **kwargs)¶ Paginates the table using a paginator and creates a
pageproperty containing information for the current page.Parameters: Extra arguments are passed to the paginator.
Pagination exceptions (
EmptyPageandPageNotAnInteger) 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.
-
attrs¶ 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.Type: dictDefault: {}This is typically used to enable a theme for a table (which is done by adding a CSS class to the
<table>element). i.e.:class SimpleTable(tables.Table): name = tables.Column() class Meta: attrs = {"class": "paleblue"}
New in version 0.15.0.
It’s possible to use callables to create dynamic values. A few caveats:
- It’s not supported for
dictkeys, i.e. only values. - All values will be resolved on table instantiation.
Consider this example where a unique
idis given to each instance of the table: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
attrskeyword argument to a table’s constructor.- It’s not supported for
-
empty_text¶ Defines the text to display when the table has no rows.
Type: unicodeDefault: NoneIf 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_textkeyword argument to a table’s constructor.
-
exclude¶ Defines which columns should be excluded from the table. This is useful in subclasses to exclude columns in a parent.
Type: tuple of unicodeDefault: ()Example:
>>> 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
excludekeyword argument to a table’s constructor.However, unlike some of the other
Table.Metaoptions, providing theexcludekeyword 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’sexcludeargument to undo an exclusion.
-
fields¶ Used in conjunction with
model, specifies which fields should have columns in the table.Type: tuple of unicodeorNoneDefault: NoneIf
None, all fields are used, otherwise only those named.Example:
# 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¶ A model to inspect and automatically create corresponding columns.
Type: Django model Default: NoneThis 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¶ The default ordering. e.g.
('name', '-age'). A hyphen-can be used to prefix a column name to indicate descending order.Type: tupleDefault: ()Note
This functionality is also available via the
order_bykeyword argument to a table’s constructor.
-
sequence¶ The sequence of the table columns. This allows the default order of columns (the order they were defined in the Table) to be overridden.
Type: any iterable (e.g. tupleorlist)Default: ()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 inheritence.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
sequencekeyword argument to a table’s constructor.
-
orderable¶ Default value for column’s orderable attribute.
Type: boolDefault: TrueIf the table and column don’t specify a value, a column’s
orderablevalue will fallback to this. object specify. This provides an easy mechanism to disable ordering on an entire table, without addingorderable=Falseto each column in a table.Note
This functionality is also available via the
orderablekeyword argument to a table’s constructor.
-
template¶ The default template to use when rendering the table.
Type: unicodeDefault: "django_tables2/table.html"Note
This functionality is also available via the template keyword argument to a table’s constructor.
-
localize¶ Specifies which fields should be localized in the table. Read Controlling localization for more information.
Type: tuple of unicodeDefault: empty tuple
-
unlocalize¶ Specifies which fields should be unlocalized in the table. Read Controlling localization for more information.
Type: tuple of unicodeDefault: empty tuple
-
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
Column¶
-
class
django_tables2.columns.Column(verbose_name=None, accessor=None, default=None, visible=True, orderable=None, attrs=None, order_by=None, sortable=None, empty_values=None, localize=None)[source]¶ Represents a single column of a table.
Columnobjects control the way a column (including the cells that fall within it) are rendered.-
attrs¶ HTML attributes for elements that make up the column.
Type: dictThis API is extended by subclasses to allow arbitrary HTML attributes to be added to the output.
By default
Columnsupports:- th –
table/thead/thelements - td –
table/tbody/tr/tdelements - cell – fallback if th or td isn’t defined
- th –
-
accessor¶ An accessor that describes how to extract values for this column from the table data.
Type: string or Accessor
-
default¶ The default value for the column. This can be a value or a callable object [1]. If an object in the data provides
Nonefor 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
QuerySetis used as the table data (since sorting is performed by the database).[1] The provided callable object must not expect to receive any arguments.
-
order_by¶ Allows one or more accessors to be used for ordering rather than accessor.
Type: unicode,tuple,Accessor
-
verbose_name¶ A human readable version of the column name.
Type: unicode
-
localize¶ - If
True, cells of this column will be localized in the HTML output by the localize filter. - If
False, cells of this column will be unlocalized in the HTML output by the unlocalize filter. - If
None(the default), cell will be rendered as is and localization will depend onUSE_L10Nsetting.
Type: bool- If
-
CheckBoxColumn¶
-
class
django_tables2.columns.CheckBoxColumn(attrs=None, **extra)[source]¶ A subclass of
Columnthat 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
nameattribute is the column name (can override via attrs argument). - orderable defaults to
False.
Note
You’d expect that you could select multiple checkboxes in the rendered table and then do something with that. This functionality isn’t implemented. If you want something to actually happen, you’ll need to implement that yourself.
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.
- HTML input’s
DateColumn¶
-
class
django_tables2.columns.DateColumn(format=None, short=True, *args, **kwargs)[source]¶ A column that renders dates in the local timezone.
Parameters: - format (
unicode) – format string in same format as Django’sdatetemplate filter (optional) - short (
bool) – if format is not specified, use Django’sSHORT_DATE_FORMATsetting, otherwise useDATE_FORMAT
- format (
DateTimeColumn¶
-
class
django_tables2.columns.DateTimeColumn(format=None, short=True, *args, **kwargs)[source]¶ A column that renders datetimes in the local timezone.
Parameters: - format (
unicode) – format string for datetime (optional) - short (
bool) – if format is not specifid, use Django’sSHORT_DATETIME_FORMAT, elseDATETIME_FORMAT
- format (
EmailColumn¶
-
class
django_tables2.columns.EmailColumn(attrs=None, *args, **kwargs)[source]¶ A subclass of
BaseLinkColumnthat renders the cell value as a hyperlink.It’s common to have a email value in a row hyperlinked to other page.
Parameters: attrs – a dictof HTML attributes that are added to the rendered<a href="...">...</a>tagExample:
# 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()
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
basenameis 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
spanis used instead:<span title="path/to/receipt.pdf">receipt.pdf</span>
Column.attrskeysaandspancan be used to add additional attributes.Parameters: verify_exists (bool) – attempt to determine if the file exists If verify_exists, the HTML class
existsormissingis added to the element to indicate the integrity of the storage.
LinkColumn¶
-
class
django_tables2.columns.LinkColumn(viewname, urlconf=None, args=None, kwargs=None, current_app=None, attrs=None, text=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
reverseand allows an internal URL to be described. The last argument attrs allows custom HTML attributes to be added to the rendered<a href="...">tag.Parameters: - viewname – See
reverse. - urlconf – See
reverse. - args – See
reverse. ** - kwargs – See
reverse. ** - current_app – See
reverse. - attrs – a
dictof HTML attributes that are added to the rendered<input type="checkbox" .../>tag - text – Either static text, or a callable. If set, this value will be used to render the text inside link instead of value (default)
** In order to create a link to a URL that relies on information in the current row,
Accessorobjects can be used in the args or kwargs arguments. The accessor will be resolved using the row’s record beforereverseis 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>.
- viewname – See
TemplateColumn¶
-
class
django_tables2.columns.TemplateColumn(template_code=None, template_name=None, **extra)[source]¶ A subclass of
Columnthat renders some template code to use as the cell value.Parameters: - template_code (
unicode) – the template code to render - template_name (
unicode) – the name of the template to render
A
Templateobject 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
recordthat 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.
Important
In order to use template tags or filters that require a
RequestContext, the table must be rendered via {% render_table %}.- template_code (
URLColumn¶
-
class
django_tables2.columns.URLColumn(attrs=None, *args, **kwargs)[source]¶ Renders URL values as hyperlinks.
Example:
>>> class CompaniesTable(tables.Table): ... www = tables.URLColumn() ... >>> table = CompaniesTable([{"www": "http://google.com"}]) >>> table.rows[0]["www"] u'<a href="http://google.com">http://google.com</a>'
Additional attributes for the
<a>tag can be specified viaattrs['a'].
See Internal APIs for internal classes.