Internal APIs¶
The items documented here are internal and subject to change.
BoundColumns¶
-
class
django_tables2.columns.BoundColumns(table, base_columns)[source]¶ Container for spawning
BoundColumnobjects.This is bound to a table and provides its
Table.columnsproperty. 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
BoundColumnsobject is a container for holdingBoundColumnobjects. It provides methods that make accessing columns easier than if they were stored in alistordict.Columnshas a similar API to adict(it actually uses aOrderedDictinternally).At the moment you’ll only come across this class when you access a
Table.columnsproperty.Parameters: table ( Table) – the table containing the columns-
__contains__(item)[source]¶ Check if a column is contained within a
BoundColumnsobject.item can either be a
BoundColumnobject, or the name of a column.
-
__getitem__(index)[source]¶ Retrieve a specific
BoundColumnobject.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
-
__init__(table, base_columns)[source]¶ Initialize self. See help(type(self)) for accurate signature.
-
__iter__()[source]¶ Convenience API, alias of
itervisible.
-
__len__()[source]¶ Return how many
BoundColumnobjects are contained (and visible).
-
__weakref__¶ list of weak references to the object (if defined)
-
iterall()[source]¶ Return an iterator that exposes all
BoundColumnobjects, regardless of visibility or sortability.
-
iteritems()[source]¶ Return an iterator of
(name, column)pairs (wherecolumnis aBoundColumn).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.
excludeandsequence).
-
iterorderable()[source]¶ Same as
BoundColumns.allbut 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).
-
itervisible()[source]¶ Same as
iterorderablebut only returns visibleBoundColumnobjects.This is geared towards table rendering.
-
BoundColumn¶
-
class
django_tables2.columns.BoundColumn(table, column, name)[source]¶ A run-time version of
Column. The difference betweenBoundColumnandColumn, is thatBoundColumnobjects include the relationship between aColumnand aTable. In practice, this means that aBoundColumnknows the “variable name” given to theColumnwhen it was declared on theTable.Parameters: -
__init__(table, column, name)[source]¶ Initialize self. See help(type(self)) for accurate signature.
-
__weakref__¶ list of weak references to the object (if defined)
-
accessor¶ Returns the string used to access data for this column out of the data source.
-
attrs¶ Proxy to
Column.attrsbut injects some values of our own.A
th,tdandtfare guaranteed to be defined (irrespective of what is actually defined in the column attrs. This makes writing templates easier.tfis not actually a HTML tag, but this key name will be used for attributes for column’s footer, if the column has one.
-
default¶ Returns the default value for this column.
-
header¶ The value that should be used in the header cell for this column.
-
localize¶ Returns
True,FalseorNoneas described inColumn.localize
-
order_by¶ Returns an
OrderByTupleof appropriately prefixed data source keys used to sort this column.See
order_by_aliasfor details.
-
order_by_alias¶ Returns an
OrderBydescribing the current state of ordering for this column.The following attempts to explain the difference between
order_byandorder_by_alias.order_by_aliasreturns andOrderByinstance 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 is 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.
e.g.:
>>> class SimpleTable(tables.Table): ... name = tables.Column(order_by=("firstname", "last_name")) ... >>> table = SimpleTable([], order_by=('-name', )) >>> table.columns["name"].order_by_alias "-name" >>> table.columns["name"].order_by ("-first_name", "-last_name")
The
OrderByreturned has been patched to include an extra attributenext, which returns a version of the alias that would be transitioned to if the user toggles sorting on this column, for example: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 %}
-
orderable¶ Return a
booldepending on whether this column supports ordering.
-
verbose_name¶ Return the verbose name for this column.
- In order of preference, this will return:
- The column’s explicitly defined
verbose_name - The model’s
verbose_namewith the first letter capitalized (if applicable) - Fall back to the column name, with first letter capitalized.
- The column’s explicitly defined
Any
verbose_namethat was not passed explicitly in the column definition is returned with the first character capitalized in keeping with the Django convention ofverbose_namebeing defined in lowercase and uppercased as needed by the application.If the table is using
QuerySetdata, then use the corresponding model field’sverbose_name. If it is 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]).
-
visible¶ Returns a
booldepending on whether this column is visible.
-
BoundRows¶
-
class
django_tables2.rows.BoundRows(data, table, pinned_data=None)[source]¶ Container for spawning
BoundRowobjects.Parameters: - data – iterable of records
- table – the
Tablein which the rows exist - pinned_data – dictionary with iterable of records for top and/or bottom pinned rows.
Example
>>> pinned_data = { ... 'top': iterable, # or None value ... 'bottom': iterable, # or None value ... }
This is used for
rows.-
__getitem__(key)[source]¶ Slicing returns a new
BoundRowsinstance, indexing returns a singleBoundRowinstance.
-
__init__(data, table, pinned_data=None)[source]¶ Initialize self. See help(type(self)) for accurate signature.
-
__weakref__¶ list of weak references to the object (if defined)
-
generator_pinned_row(data)[source]¶ Top and bottom pinned rows generator.
Parameters: data – Iterable data for all records for top or bottom pinned rows. Yields: BoundPinnedRow – Top or bottom BoundPinnedRowobject for single pinned record.
BoundRow¶
-
class
django_tables2.rows.BoundRow(record, table)[source]¶ Represents a specific row in a table.
BoundRowobjects are a container that make it easy to access the final ‘rendered’ values for cells in a row. You can simply iterate over aBoundRowobject 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) ... 1 <input type="checkbox" name="my_chkbox" value="2" />
Alternatively you can use row.cells[0] to retrieve a specific cell:
>>> row.cells[0] 1 >>> row.cells[1] '<input type="checkbox" name="my_chkbox" value="2" />' >>> row.cells[2] ... IndexError: list index out of range
Finally you can also use the column names to retrieve a specific cell:
>>> row.cells.a 1 >>> row.cells.b '<input type="checkbox" name="my_chkbox" value="2" />' >>> row.cells.c ... KeyError: "Column with name 'c' does not exist; choices are: ['a', 'b']"
If you have the column name in a variable, you can also treat the
cellsproperty like adict:>>> key = 'a' >>> row.cells[key] 1
Parameters: - table – The
Tablein which this row exists. - record – a single record from the table data that is used to
populate the row. A record could be a
Modelobject, adict, or something else.
-
__iter__()[source]¶ 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.
-
__weakref__¶ list of weak references to the object (if defined)
-
_call_render(bound_column, value=None)[source]¶ Call the column’s render method with appropriate kwargs
-
_call_value(bound_column, value=None)[source]¶ Call the column’s value method with appropriate kwargs
-
_optional_cell_arguments(bound_column, value)[source]¶ Defines the arguments that will optionally be passed while calling the cell’s rendering or value getter if that function has one of these as a keyword argument.
-
attrs¶ Return the attributes for a certain row.
-
get_cell(name)[source]¶ Returns the final rendered html for a cell in the row, given the name of a column.
-
get_cell_value(name)[source]¶ Returns the final rendered value (excluding any html) for a cell in the row, given the name of a column.
-
get_even_odd_css_class()[source]¶ Return css class, alternating for odd and even records.
Returns: evenfor even records,oddotherwise.Return type: string
-
items()[source]¶ Returns iterator yielding
(bound_column, cell)pairs.cell is
row[name]– the rendered unicode value that should berendered within ``<td>.
-
record¶ The data record from the data source which is used to populate this row with data.
- table – The
TableData¶
-
class
django_tables2.tables.TableData(data)[source]¶ Base class for table data containers.
-
__getitem__(key)[source]¶ Slicing returns a new
TableDatainstance, indexing returns a single record.
-
__iter__()[source]¶ 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).
-
__weakref__¶ list of weak references to the object (if defined)
-
utils¶
-
class
django_tables2.utils.Sequence[source]¶ Represents a column sequence, e.g.
('first_name', '...', 'last_name')This is used to represent
Table.Meta.sequenceor theTableconstructors’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 are not explicitly specified.
-
__weakref__¶ list of weak references to the object (if defined)
-
-
class
django_tables2.utils.OrderBy[source]¶ A single item in an
OrderByTupleobject.This class is essentially just a
strwith some extra properties.-
__weakref__¶ list of weak references to the object (if defined)
-
bare¶ the bare form.
The bare form is the non-prefixed form. Typically the bare form is just the ascending form.
Example:
ageis the bare form of-ageType: Returns Type: OrderBy
-
for_queryset()[source]¶ Returns the current instance usable in Django QuerySet’s order_by arguments.
-
is_ascending¶ Returns
Trueif this object induces ascending ordering.
-
is_descending¶ Returns
Trueif this object induces descending ordering.
-
-
class
django_tables2.utils.OrderByTuple[source]¶ Stores ordering as (as
OrderByobjects).The
order_byproperty is always converted to anOrderByTupleobject. This class is essentially just atuplewith some useful extras.Example:
>>> x = OrderByTuple(('name', '-age')) >>> x['age'] '-age' >>> x['age'].is_descending True >>> x['age'].opposite 'age'
-
__contains__(name)[source]¶ Determine if a column has an influence on ordering.
Example:
>>> x = OrderByTuple(('name', )) >>> 'name' in x True >>> '-name' in x True
Parameters: name (str) – The name of a column. (optionally prefixed) Returns: Trueif the column withnameinfluences the ordering.Return type: bool
-
__getitem__(index)[source]¶ Allows an
OrderByobject 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] 'name' >>> x['age'] '-age' >>> x['-age'] '-age'
Parameters: index (int) – Index to query the ordering for. Returns: for the ordering at the index. Return type: OrderBy
-
static
__new__(cls, iterable)[source]¶ Create and return a new object. See help(type) for accurate signature.
-
get(key, fallback)[source]¶ Identical to
__getitem__, but supports fallback value.
-
-
class
django_tables2.utils.Accessor[source] A string describing a path from one object to another via attribute/index accesses. For convenience, the class has an alias
Ato allow for more concise code.Relations are separated by a
.character.-
__weakref__ list of weak references to the object (if defined)
-
get_field(model)[source] Return the django model field for model in context, following relations.
-
penultimate(context, quiet=True)[source] - Split the accessor on the right-most dot ‘.’, return a tuple with:
- the resolved left part.
- the remainder
Example:
>>> Accessor("a.b.c").penultimate({"a": {"a": 1, "b": {"c": 2, "d": 4}}}) ({"c": 2, "d": 4}, "c")
-
resolve(context, safe=True, quiet=False)[source] 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.
Example:
>>> x = Accessor('__len__') >>> x.resolve('brad') 4 >>> x = Accessor('0.upper') >>> x.resolve('brad') 'B'
Parameters: - context – 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
Returns: target object
Raises: - TypeError`,
AttributeError,KeyError,ValueError - (unless
quiet==True)
- dictionary (e.g.
-
-
class
django_tables2.utils.AttributeDict[source] A wrapper around
collections.OrderedDictthat knows how to render itself as HTML style tag attributes.Any key with
value is Nonewill be skipped.The returned string is marked safe, so it can be used safely in a template. See
as_htmlfor a usage example.-
as_html()[source] Render to HTML tag attributes.
Example:
>>> from django_tables2.utils import AttributeDict >>> attrs = AttributeDict({'class': 'mytable', 'id': 'someid'}) >>> attrs.as_html() 'class="mytable" id="someid"'
returns:
SafeUnicodeobject
-
-
django_tables2.utils.signature(fn)[source] Returns: - 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)[source] Calls the function
fnwith the keyword arguments fromkwargsit expectsIf the kwargs argument is defined, pass all arguments, else provide exactly the arguments wanted.
If one of the arguments of
fnare not contained in kwargs,fnwill not be called andNonewill be returned.
-
django_tables2.utils.computed_values(d, kwargs=None)[source] Returns a new
dictthat has callable values replaced with the return values.Example:
>>> compute_values({'foo': lambda: 'bar'}) {'foo': 'bar'}
Arbitrarily deep structures are supported. The logic is as follows:
- If the value is callable, call it and make that the new value.
- If the value is an instance of dict, use ComputableDict to compute its keys.
Example:
>>> def parents(): ... return { ... 'father': lambda: 'Foo', ... 'mother': 'Bar' ... } ... >>> a = { ... 'name': 'Brad', ... 'parents': parents ... } ... >>> computed_values(a) {'name': 'Brad', 'parents': {'father': 'Foo', 'mother': 'Bar'}}
Parameters: - d (dict) – The original dictionary.
- kwargs – any extra keyword arguments will be passed to the callables, if the callable takes an argument with such a name.
Returns: with callable values replaced.
Return type: dict