Horizon DataTables

Horizon includes a componentized API for programmatically creating tables in the UI. Why would you want this? It means that every table renders correctly and consistently, table- and row-level actions all have a consistent API and appearance, and generally you don’t have to reinvent the wheel or copy-and-paste every time you need a new table!

See also

For usage information, tips & tricks and more examples check out the DataTables Topic Guide.

DataTable

The core class which defines the high-level structure of the table being represented. Example:

class MyTable(DataTable):
    name = Column('name')
    email = Column('email')

    class Meta:
        name = "my_table"
        table_actions = (MyAction, MyOtherAction)
        row_actions - (MyAction)

A full reference is included below:

class horizon.tables.DataTable(request, data=None, needs_form_wrapper=None, **kwargs)

A class which defines a table with all data and associated actions.

name

String. Read-only access to the name specified in the table’s Meta options.

multi_select

Boolean. Read-only access to whether or not this table should display a column for multi-select checkboxes.

data

Read-only access to the data this table represents.

filtered_data

Read-only access to the data this table represents, filtered by the filter() method of the table’s FilterAction class (if one is provided) using the current request’s query parameters.

calculate_row_status(statuses)

Returns a boolean value determining the overall row status based on the dictionary of column name to status mappings passed in.

By default, it uses the following logic:

  1. If any statuses are False, return False.
  2. If no statuses are False but any or None, return None.
  3. If all statuses are True, return True.

This provides the greatest protection against false positives without weighting any particular columns.

The statuses parameter is passed in as a dictionary mapping column names to their statuses in order to allow this function to be overridden in such a way as to weight one column’s status over another should that behavior be desired.

classmethod check_handler(request)

Determine whether the request should be handled by this table.

get_absolute_url()

Returns the canonical URL for this table.

This is used for the POST action attribute on the form element wrapping the table. In many cases it is also useful for redirecting after a successful action on the table.

For convenience it defaults to the value of request.get_full_path() with any query string stripped off, e.g. the path at which the table was requested.

get_columns()

Returns this table’s columns including auto-generated ones.

get_empty_message()

Returns the message to be displayed when there is no data.

get_full_url()

Returns the full URL path for this table.

This is used for the POST action attribute on the form element wrapping the table. We use this method to persist the pagination marker.

get_marker()

Returns the identifier for the last object in the current data set for APIs that use marker/limit-based paging.

get_object_by_id(lookup)

Returns the data object from the table’s dataset which matches the lookup parameter specified. An error will be raised if the match is not a single data object.

We will convert the object id and lookup to unicode before comparison.

Uses get_object_id() internally.

get_object_display(datum)

Returns a display name that identifies this object.

By default, this returns a name attribute from the given object, but this can be overridden to return other values.

get_object_id(datum)

Returns the identifier for the object this row will represent.

By default this returns an id attribute on the given object, but this can be overridden to return other values.

Warning

Make sure that the value returned is a unique value for the id otherwise rendering issues can occur.

get_pagination_string()

Returns the query parameter string to paginate this table.

get_row_actions(datum)

Returns a list of the action instances for a specific row.

get_row_status_class(status)

Returns a css class name determined by the status value. This class name is used to indicate the status of the rows in the table if any status_columns have been specified.

get_rows()

Return the row data for this table broken out by columns.

get_table_actions()

Returns a list of the action instances for this table.

has_actions

Boolean. Indicates whether there are any available actions on this table.

has_more_data()

Returns a boolean value indicating whether there is more data available to this table from the source (generally an API).

The method is largely meant for internal use, but if you want to override it to provide custom behavior you can do so at your own risk.

inline_edit_handle(request, table_name, action_name, obj_id, new_row)

Inline edit handler.

Showing form or handling update by POST of the cell.

inline_update_action(request, datum, cell, obj_id, cell_name)

Handling update by POST of the cell.

maybe_handle()

Determine whether the request should be handled by any action on this table after data has been loaded.

maybe_preempt()

Determine whether the request should be handled by a preemptive action on this table or by an AJAX row update before loading any data.

needs_form_wrapper

Boolean. Indicates whether this table should be rendered wrapped in a <form> tag or not.

static parse_action(action_string)

Parses the action parameter (a string) sent back with the POST data. By default this parses a string formatted as {{ table_name }}__{{ action_name }}__{{ row_id }} and returns each of the pieces. The row_id is optional.

render()

Renders the table using the template from the table options.

render_row_actions(datum)

Renders the actions specified in Meta.row_actions using the current row data.

render_table_actions()

Renders the actions specified in Meta.table_actions.

sanitize_id(obj_id)

Override to modify an incoming obj_id to match existing API data types or modify the format.

set_multiselect_column_visibility(visible=True)

hide checkbox column if no current table action is allowed.

take_action(action_name, obj_id=None, obj_ids=None)

Locates the appropriate action and routes the object data to it. The action should return an HTTP redirect if successful, or a value which evaluates to False if unsuccessful.

DataTable Options

The following options can be defined in a Meta class inside a DataTable class. Example:

class MyTable(DataTable):
    class Meta:
        name = "my_table"
        verbose_name = "My Table"
class horizon.tables.base.DataTableOptions(options)[source]

Contains options for DataTable objects.

name

A short name or slug for the table.

verbose_name

A more verbose name for the table meant for display purposes.

columns

A list of column objects or column names. Controls ordering/display of the columns in the table.

table_actions

A list of action classes derived from the Action class. These actions will handle tasks such as bulk deletion, etc. for multiple objects at once.

row_actions

A list similar to table_actions except tailored to appear for each row. These actions act on a single object at a time.

actions_column

Boolean value to control rendering of an additional column containing the various actions for each row. Defaults to True if any actions are specified in the row_actions option.

multi_select

Boolean value to control rendering of an extra column with checkboxes for selecting multiple objects in the table. Defaults to True if any actions are specified in the table_actions option.

filter

Boolean value to control the display of the “filter” search box in the table actions. By default it checks whether or not an instance of FilterAction is in table_actions.

template

String containing the template which should be used to render the table. Defaults to "horizon/common/_data_table.html".

context_var_name

The name of the context variable which will contain the table when it is rendered. Defaults to "table".

pagination_param

The name of the query string parameter which will be used when paginating this table. When using multiple tables in a single view this will need to be changed to differentiate between the tables. Default: "marker".

status_columns

A list or tuple of column names which represents the “state” of the data object being represented.

If status_columns is set, when the rows are rendered the value of this column will be used to add an extra class to the row in the form of "status_up" or "status_down" for that row’s data.

The row status is used by other Horizon components to trigger tasks such as dynamic AJAX updating.

cell_class

The class which should be used for rendering the cells of this table. Optional. Default: Cell.

row_class

The class which should be used for rendering the rows of this table. Optional. Default: Row.

column_class

The class which should be used for handling the columns of this table. Optional. Default: Column.

mixed_data_type

A toggle to indicate if the table accepts two or more types of data. Optional. Default: :False

data_types

A list of data types that this table would accept. Default to be an empty list, but if the attribute mixed_data_type is set to True, then this list must have at least one element.

data_type_name

The name of an attribute to assign to data passed to the table when it accepts mix data. Default: "_table_data_type"

footer

Boolean to control whether or not to show the table’s footer. Default: True.

permissions

A list of permission names which this table requires in order to be displayed. Defaults to an empty list ([]).

FormsetDataTable

You can integrate the DataTable with a Django Formset using one of following classes:

class horizon.tables.formset.FormsetDataTableMixin(*args, **kwargs)[source]

A mixin for DataTable to support Django Formsets.

This works the same as the FormsetDataTable below, but can be used to add to existing DataTable subclasses.

get_empty_row()[source]

Return a row with no data, for adding at the end of the table.

get_formset()[source]

Provide the formset corresponding to this DataTable.

Use this to validate the formset and to get the submitted data back.

get_required_columns()[source]

Lists names of columns that have required fields.

get_rows()[source]

Return the row data for this table broken out by columns.

The row objects get an additional form parameter, with the formset form corresponding to that row.

class horizon.tables.formset.FormsetDataTable(*args, **kwargs)[source]

A DataTable with support for Django Formsets.

Note that horizon.tables.DataTableOptions.row_class and horizon.tables.DataTaleOptions.cell_class are overwritten in this class, so setting them in Meta has no effect.

formset_class

A class made with django.forms.formsets.formset_factory containing the definition of the formset to use with this data table.

The columns that are named the same as the formset fields will be replaced with form widgets in the table. Any hidden fields from the formset will also be included. The fields that are not hidden and don’t correspond to any column will not be included in the form.

Table Components

class horizon.tables.Column(transform, verbose_name=None, sortable=True, link=None, allowed_data_types=[], hidden=False, attrs=None, status=False, status_choices=None, display_choices=None, empty_value=None, filters=None, classes=None, summation=None, auto=None, truncate=None, link_classes=None, wrap_list=False, form_field=None, form_field_attributes=None, update_action=None)

A class which represents a single column in a DataTable.

transform

A string or callable. If transform is a string, it should be the name of the attribute on the underlying data class which should be displayed in this column. If it is a callable, it will be passed the current row’s data at render-time and should return the contents of the cell. Required.

verbose_name

The name for this column which should be used for display purposes. Defaults to the value of transform with the first letter of each word capitalized if the transform is not callable, otherwise it defaults to an empty string ("").

sortable

Boolean to determine whether this column should be sortable or not. Defaults to True.

hidden

Boolean to determine whether or not this column should be displayed when rendering the table. Default: False.

A string or callable which returns a URL which will be wrapped around this column’s text as a link.

allowed_data_types

A list of data types for which the link should be created. Default is an empty list ([]).

When the list is empty and the link attribute is not None, all the rows under this column will be links.

status

Boolean designating whether or not this column represents a status (i.e. “enabled/disabled”, “up/down”, “active/inactive”). Default: False.

status_choices

A tuple of tuples representing the possible data values for the status column and their associated boolean equivalent. Positive states should equate to True, negative states should equate to False, and indeterminate states should be None.

Values are compared in a case-insensitive manner.

Example (these are also the default values):

status_choices = (
        ('enabled', True),
        ('true', True)
        ('up', True),
        ('active', True),
        ('yes', True),
        ('on', True),
        ('none', None),
        ('unknown', None),
        ('', None),
        ('disabled', False),
        ('down', False),
        ('false', False),
        ('inactive', False),
        ('no', False),
        ('off', False),
    )
display_choices

A tuple of tuples representing the possible values to substitute the data when displayed in the column cell.

empty_value

A string or callable to be used for cells which have no data. Defaults to the string "-".

summation

A string containing the name of a summation method to be used in the generation of a summary row for this column. By default the options are "sum" or "average", which behave as expected. Optional.

filters

A list of functions (often template filters) to be applied to the value of the data for this column prior to output. This is effectively a shortcut for writing a custom transform function in simple cases.

classes

An iterable of CSS classes which should be added to this column. Example: classes=('foo', 'bar').

attrs

A dict of HTML attribute strings which should be added to this column. Example: attrs={"data-foo": "bar"}.

truncate

An integer for the maximum length of the string in this column. If the data in this column is larger than the supplied number, the data for this column will be truncated and an ellipsis will be appended to the truncated data. Defaults to None.

An iterable of CSS classes which will be added when the column’s text is displayed as a link. Example: classes=('link-foo', 'link-bar'). Defaults to None.

wrap_list

Boolean value indicating whether the contents of this cell should be wrapped in a <ul></ul> tag. Useful in conjunction with Django’s unordered_list template filter. Defaults to False.

form_field

A form field used for inline editing of the column. A django forms.Field can be used or django form.Widget can be used.

Example: form_field=forms.CharField(required=True). Defaults to None.

form_field_attributes

The additional html attributes that will be rendered to form_field. Example: form_field_attributes={'class': 'bold_input_field'}. Defaults to None.

update_action

The class that inherits from tables.actions.UpdateAction, update_cell method takes care of saving inline edited data. The tables.base.Row get_data method needs to be connected to table for obtaining the data. Example: update_action=UpdateCell. Defaults to None.

get_data(datum)

Returns the final display data for this column from the given inputs.

The return value will be either the attribute specified for this column or the return value of the attr:~horizon.tables.Column.transform method for this column.

Returns the final value for the column’s link property.

If allowed_data_types of this column is not empty and the datum has an assigned type, check if the datum’s type is in the allowed_data_types list. If not, the datum won’t be displayed as a link.

If link is a callable, it will be passed the current data object and should return a URL. Otherwise get_link_url will attempt to call reverse on link with the object’s id as a parameter. Failing that, it will simply return the value of link.

get_raw_data(datum)

Returns the raw data for this column, before any filters or formatting are applied to it. This is useful when doing calculations on data in the table.

get_summation()

Returns the summary value for the data in this column if a valid summation method is specified for it. Otherwise returns None.

class horizon.tables.Row(table, datum=None)

Represents a row in the table.

When iterated, the Row instance will yield each of its cells.

Rows are capable of AJAX updating, with a little added work:

The ajax property needs to be set to True, and subclasses need to define a get_data method which returns a data object appropriate for consumption by the table (effectively the “get” lookup versus the table’s “list” lookup).

The automatic update interval is configurable by setting the key ajax_poll_interval in the HORIZON_CONFIG dictionary. Default: 2500 (measured in milliseconds).

table

The table which this row belongs to.

datum

The data object which this row represents.

id

A string uniquely representing this row composed of the table name and the row data object’s identifier.

cells

The cells belonging to this row stored in a SortedDict object. This attribute is populated during instantiation.

status

Boolean value representing the status of this row calculated from the values of the table’s status_columns if they are set.

status_class

Returns a css class for the status of the row based on status.

ajax

Boolean value to determine whether ajax updating for this row is enabled.

ajax_action_name

String that is used for the query parameter key to request AJAX updates. Generally you won’t need to change this value. Default: "row_update".

ajax_cell_action_name

String that is used for the query parameter key to request AJAX updates of cell. Generally you won’t need to change this value. It is also used for inline edit of the cell. Default: "cell_update".

can_be_selected(datum)

By default if multiselect enabled return True. You can remove the checkbox after an ajax update here if required.

get_cells()

Returns the bound cells for this row in order.

get_data(request, obj_id)

Fetches the updated data for the row based on the object id passed in. Must be implemented by a subclass to allow AJAX updating.

load_cells(datum=None)

Load the row’s data (either provided at initialization or as an argument to this function), initiailize all the cells contained by this row, and set the appropriate row properties which require the row’s data to be determined.

This function is called automatically by __init__() if the datum argument is provided. However, by not providing the data during initialization this function allows for the possibility of a two-step loading pattern when you need a row instance but don’t yet have the data available.

Actions

class horizon.tables.Action(single_func=None, multiple_func=None, handle_func=None, attrs=None, **kwargs)

Represents an action which can be taken on this table’s data.

name

Required. The short name or “slug” representing this action. This name should not be changed at runtime.

verbose_name

A descriptive name used for display purposes. Defaults to the value of name with the first letter of each word capitalized.

verbose_name_plural

Used like verbose_name in cases where handles_multiple is True. Defaults to verbose_name with the letter “s” appended.

method

The HTTP method for this action. Defaults to POST. Other methods may or may not succeed currently.

requires_input

Boolean value indicating whether or not this action can be taken without any additional input (e.g. an object id). Defaults to True.

preempt

Boolean value indicating whether this action should be evaluated in the period after the table is instantiated but before the data has been loaded.

This can allow actions which don’t need access to the full table data to bypass any API calls and processing which would otherwise be required to load the table.

allowed_data_types

A list that contains the allowed data types of the action. If the datum’s type is in this list, the action will be shown on the row for the datum.

Default to be an empty list ([]). When set to empty, the action will accept any kind of data.

policy_rules

list of scope and rule tuples to do policy checks on, the composition of which is (scope, rule)

scope: service type managing the policy for action rule: string representing the action to be checked

for a policy that requires a single rule check:
policy_rules should look like
“((“compute”, “compute:create_instance”),)”
for a policy that requires multiple rule checks:
rules should look like
“((“identity”, “identity:list_users”),
(“identity”, “identity:list_roles”))”

At least one of the following methods must be defined:

single(self, data_table, request, object_id)

Handler for a single-object action.

multiple(self, data_table, request, object_ids)

Handler for multi-object actions.

handle(self, data_table, request, object_ids)

If a single function can work for both single-object and multi-object cases then simply providing a handle function will internally route both single and multiple requests to handle with the calls from single being transformed into a list containing only the single object id.

get_param_name()

Returns the full POST parameter name for this action.

Defaults to {{ table.name }}__{{ action.name }}.

class horizon.tables.LinkAction(attrs=None, **kwargs)

A table action which is simply a link rather than a form POST.

name

Required. The short name or “slug” representing this action. This name should not be changed at runtime.

verbose_name

A string which will be rendered as the link text. (Required)

url

A string or a callable which resolves to a url to be used as the link target. You must either define the url attribute or override the get_link_url method on the class.

allowed_data_types

A list that contains the allowed data types of the action. If the datum’s type is in this list, the action will be shown on the row for the datum.

Defaults to be an empty list ([]). When set to empty, the action will accept any kind of data.

Returns the final URL based on the value of url.

If url is callable it will call the function. If not, it will then try to call reverse on url. Failing that, it will simply return the value of url as-is.

When called for a row action, the current row data object will be passed as the first parameter.

class horizon.tables.FilterAction(**kwargs)

A base class representing a filter action for a table.

name

The short name or “slug” representing this action. Defaults to "filter".

verbose_name

A descriptive name used for display purposes. Defaults to the value of name with the first letter of each word capitalized.

param_name

A string representing the name of the request parameter used for the search term. Default: "q".

filter(table, data, filter_string)

Provides the actual filtering logic.

This method must be overridden by subclasses and return the filtered data.

get_param_name()

Returns the full query parameter name for this action.

Defaults to {{ table.name }}__{{ action.name }}__{{ action.param_name }}.

class horizon.tables.BatchAction(**kwargs)

A table action which takes batch action on one or more objects. This action should not require user input on a per-object basis.

name

An internal name for this action.

action_present

String or tuple/list. The display forms of the name. Should be a transitive verb, capitalized and translated. (“Delete”, “Rotate”, etc.) If tuple or list - then setting self.current_present_action = n will set the current active item from the list(action_present[n])

You can pass a complete action name including ‘data_type’ by specifying ‘%(data_type)s’ substitution in action_present (“Delete %(data_type)s”). Otherwise a complete action name is a format of “<action> <data_type>”. <data_type> is determined based on the number of items. By passing a complete action name you allow translators to control the order of words as they want.

action_past

String or tuple/list. The past tense of action_present. (“Deleted”, “Rotated”, etc.) If tuple or list - then setting self.current_past_action = n will set the current active item from the list(action_past[n])

data_type_singular

A display name for the type of data that receives the action. (“Key Pair”, “Floating IP”, etc.)

data_type_plural

Optional plural word for the type of data being acted on. Defaults to appending ‘s’. Relying on the default is bad for translations and should not be done.

success_url

Optional location to redirect after completion of the delete action. Defaults to the current page.

action(request, datum_id)

Required. Accepts a single object id and performs the specific action.

Return values are discarded, errors raised are caught and logged.

get_success_url(request=None)

Returns the URL to redirect to after a successful action.

update(request, datum)

Switches the action verbose name, if needed.

class horizon.tables.DeleteAction(**kwargs)

Doc missing.

class horizon.tables.UpdateAction

A table action for cell updates by inline editing.

allowed(request, datum, cell)

Determine whether updating is allowed for the current request.

This method is meant to be overridden with more specific checks. Data of the row and of the cell are passed to the method.

update_cell(request, datum, obj_id, cell_name, new_cell_value)

Method for saving data of the cell.

This method must implements saving logic of the inline edited table cell.

Class-Based Views

Several class-based views are provided to make working with DataTables easier in your UI.

class horizon.tables.DataTableView(*args, **kwargs)

A class-based generic view to handle basic DataTable processing.

Three steps are required to use this view: set the table_class attribute with the desired DataTable class; define a get_data method which returns a set of data for the table; and specify a template for the template_name attribute.

Optionally, you can override the has_more_data method to trigger pagination handling for APIs that support it.

class horizon.tables.MultiTableView(*args, **kwargs)

A class-based generic view to handle the display and processing of multiple DataTable classes in a single view.

Three steps are required to use this view: set the table_classes attribute with a tuple of the desired DataTable classes; define a get_{{ table_name }}_data method for each table class which returns a set of data for that table; and specify a template for the template_name attribute.

Table Of Contents

Previous topic

Horizon Workflows

Next topic

Horizon Tabs and TabGroups

This Page