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.
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:
A class which defines a table with all data and associated actions.
String. Read-only access to the name specified in the table’s Meta options.
Boolean. Read-only access to whether or not this table should display a column for multi-select checkboxes.
Read-only access to the data this table represents.
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.
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:
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.
Determine whether the request should be handled by this table.
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.
Returns this table’s columns including auto-generated ones.
Returns the message to be displayed when there is no data.
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.
Returns the identifier for the last object in the current data set for APIs that use marker/limit-based paging.
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.
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.
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.
Returns the query parameter string to paginate this table.
Returns a list of the action instances for a specific row.
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.
Return the row data for this table broken out by columns.
Returns a list of the action instances for this table.
Boolean. Indicates whether there are any available actions on this table.
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 handler.
Showing form or handling update by POST of the cell.
Handling update by POST of the cell.
Determine whether the request should be handled by any action on this table after data has been loaded.
Determine whether the request should be handled by a preemptive action on this table or by an AJAX row update before loading any data.
Boolean. Indicates whether this table should be rendered wrapped in a <form> tag or not.
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.
Renders the table using the template from the table options.
Renders the actions specified in Meta.row_actions using the current row data.
Renders the actions specified in Meta.table_actions.
Override to modify an incoming obj_id to match existing API data types or modify the format.
hide checkbox column if no current table action is allowed.
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.
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"
Contains options for DataTable objects.
A short name or slug for the table.
A more verbose name for the table meant for display purposes.
A list of column objects or column names. Controls ordering/display of the columns in the table.
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.
A list similar to table_actions except tailored to appear for each row. These actions act on a single object at a time.
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.
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.
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.
String containing the template which should be used to render the table. Defaults to "horizon/common/_data_table.html".
The name of the context variable which will contain the table when it is rendered. Defaults to "table".
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".
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.
The class which should be used for rendering the cells of this table. Optional. Default: Cell.
The class which should be used for rendering the rows of this table. Optional. Default: Row.
The class which should be used for handling the columns of this table. Optional. Default: Column.
A toggle to indicate if the table accepts two or more types of data. Optional. Default: :False
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.
The name of an attribute to assign to data passed to the table when it accepts mix data. Default: "_table_data_type"
Boolean to control whether or not to show the table’s footer. Default: True.
A list of permission names which this table requires in order to be displayed. Defaults to an empty list ([]).
You can integrate the DataTable with a Django Formset using one of following classes:
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.
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.
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.
A class which represents a single column in a DataTable.
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.
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 ("").
Boolean to determine whether this column should be sortable or not. Defaults to True.
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.
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.
Boolean designating whether or not this column represents a status (i.e. “enabled/disabled”, “up/down”, “active/inactive”). Default: False.
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),
)
A tuple of tuples representing the possible values to substitute the data when displayed in the column cell.
A string or callable to be used for cells which have no data. Defaults to the string "-".
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.
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.
An iterable of CSS classes which should be added to this column. Example: classes=('foo', 'bar').
A dict of HTML attribute strings which should be added to this column. Example: attrs={"data-foo": "bar"}.
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.
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.
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.
The additional html attributes that will be rendered to form_field. Example: form_field_attributes={'class': 'bold_input_field'}. Defaults to None.
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.
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.
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.
Returns the summary value for the data in this column if a valid summation method is specified for it. Otherwise returns 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).
The table which this row belongs to.
The data object which this row represents.
A string uniquely representing this row composed of the table name and the row data object’s identifier.
The cells belonging to this row stored in a SortedDict object. This attribute is populated during instantiation.
Boolean value representing the status of this row calculated from the values of the table’s status_columns if they are set.
Returns a css class for the status of the row based on status.
Boolean value to determine whether ajax updating for this row is enabled.
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".
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".
By default if multiselect enabled return True. You can remove the checkbox after an ajax update here if required.
Returns the bound cells for this row in order.
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 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.
Represents an action which can be taken on this table’s data.
Required. The short name or “slug” representing this action. This name should not be changed at runtime.
A descriptive name used for display purposes. Defaults to the value of name with the first letter of each word capitalized.
Used like verbose_name in cases where handles_multiple is True. Defaults to verbose_name with the letter “s” appended.
The HTTP method for this action. Defaults to POST. Other methods may or may not succeed currently.
Boolean value indicating whether or not this action can be taken without any additional input (e.g. an object id). Defaults to True.
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.
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.
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:
Handler for a single-object action.
Handler for multi-object actions.
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.
Returns the full POST parameter name for this action.
Defaults to {{ table.name }}__{{ action.name }}.
A table action which is simply a link rather than a form POST.
Required. The short name or “slug” representing this action. This name should not be changed at runtime.
A string which will be rendered as the link text. (Required)
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.
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.
A base class representing a filter action for a table.
The short name or “slug” representing this action. Defaults to "filter".
A descriptive name used for display purposes. Defaults to the value of name with the first letter of each word capitalized.
A string representing the name of the request parameter used for the search term. Default: "q".
Provides the actual filtering logic.
This method must be overridden by subclasses and return the filtered data.
Returns the full query parameter name for this action.
Defaults to {{ table.name }}__{{ action.name }}__{{ action.param_name }}.
A table action which takes batch action on one or more objects. This action should not require user input on a per-object basis.
An internal name for this action.
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.
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])
A display name for the type of data that receives the action. (“Key Pair”, “Floating IP”, etc.)
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.
Optional location to redirect after completion of the delete action. Defaults to the current page.
Required. Accepts a single object id and performs the specific action.
Return values are discarded, errors raised are caught and logged.
Returns the URL to redirect to after a successful action.
Switches the action verbose name, if needed.
Doc missing.
A table action for cell updates by inline editing.
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.
Method for saving data of the cell.
This method must implements saving logic of the inline edited table cell.
Several class-based views are provided to make working with DataTables easier in your UI.
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.
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.