The horizon.tables.base Module

class horizon.tables.base.Cell(datum, column, row, attrs=None, classes=None)[source]

Bases: horizon.utils.html.HTMLElement

Represents a single cell in the table.

get_ajax_update_url()[source]
get_data(datum, column, row)[source]

Fetches the data to be displayed in this cell.

get_default_classes()[source]

Returns a flattened string of the cell’s CSS classes.

get_status_class(status)[source]

Returns a css class name determined by the status value.

id[source]
render()[source]
status[source]

Gets the status for the column based on the cell’s data.

update_allowed[source]

Determines whether update of given cell is allowed.

Calls allowed action of defined UpdateAction of the Column.

url[source]
value[source]

Returns a formatted version of the data for final output.

This takes into consideration the link` and empty_value attributes.

class horizon.tables.base.Column(transform, verbose_name=None, sortable=True, link=None, allowed_data_types=None, 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, link_attrs=None, cell_attributes_getter=None, help_text=None)[source]

Bases: horizon.utils.html.HTMLElement

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"}.

cell_attributes_getter

A callable to get the HTML attributes of a column cell depending on the data. For example, to add additional description or help information for data in a column cell (e.g. in Images panel, for the column ‘format’):

helpText = {
  'ARI':'Amazon Ramdisk Image',
  'QCOW2':'QEMU' Emulator'
  }

getHoverHelp(data):
  text = helpText.get(data, None)
  if text:
      return {'title': text}
  else:
      return {}
...
...
cell_attributes_getter = getHoverHelp
truncate

An integer for the maximum length of the string in this column. If the length of 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. This is left for backward compatibility. Deprecated in favor of the link_attributes attribute. Example: link_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.

A dict of HTML attribute strings which should be added when the column’s text is displayed as a link. Examples: link_attrs={"data-foo": "bar"}. link_attrs={"target": "_blank", "class": "link-foo link-bar"}. Defaults to None.

help_text

A string of simple help text displayed in a tooltip when you hover over the help icon beside the Column name. Defaults to None.

creation_counter = 0
get_data(datum)[source]

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.

get_default_attrs()[source]
get_link_url(datum)[source]

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)[source]

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()[source]

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

name = None
status_choices = (('enabled', True), ('true', True), ('up', True), ('yes', True), ('active', True), ('on', True), ('none', None), ('unknown', None), ('', None), ('disabled', False), ('down', False), ('false', False), ('inactive', False), ('no', False), ('off', False))
summation_methods = {'sum': <built-in function sum>, 'average': <function <lambda> at 0x7faf8a0c3de8>}
transform = None
verbose_name = None
class horizon.tables.base.DataTable(request, data=None, needs_form_wrapper=None, **kwargs)[source]

Bases: object

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

name[source]

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

multi_select[source]

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[source]

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.

base_actions = OrderedDict()
base_columns = OrderedDict()
calculate_row_status(statuses)[source]

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)[source]

Determine whether the request should be handled by this table.

css_classes()[source]

Returns the additional CSS class to be added to <table> tag.

filtered_data[source]
footer[source]
get_absolute_url()[source]

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()[source]

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

get_empty_message()[source]

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

get_filter_field()[source]

Get the filter field value used for ‘server’ type filters. This is the value from the filter action’s list of filter choices.

get_filter_string()[source]

Get the filter string value. For ‘server’ type filters this is saved in the session so that it gets persisted across table loads. For other filter types this is obtained from the POST dict.

get_full_url()[source]

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()[source]

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)[source]

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)[source]

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)[source]

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()[source]

Returns the query parameter string to paginate this table to the next page.

get_prev_marker()[source]

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

get_prev_pagination_string()[source]

Returns the query parameter string to paginate this table to the previous page.

get_row_actions(datum)[source]

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

get_row_status_class(status)[source]

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()[source]

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

get_table_actions()[source]

Returns a list of the action instances for this table.

has_actions[source]

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

has_more_data()[source]

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.

has_prev_data()[source]

Returns a boolean value indicating whether there is previous 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)[source]

Inline edit handler.

Showing form or handling update by POST of the cell.

inline_update_action(request, datum, cell, obj_id, cell_name)[source]

Handling update by POST of the cell.

is_browser_table()[source]
maybe_handle()[source]

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

maybe_preempt()[source]

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

multi_select[source]
name[source]
needs_form_wrapper[source]

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

static parse_action(action_string)[source]

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()[source]

Renders the table using the template from the table options.

render_row_actions(datum, pull_right=True, row=False)[source]

Renders the actions specified in Meta.row_actions using the current row data. If row is True, the actions are rendered in a row of buttons. Otherwise they are rendered in a dropdown box.

render_table_actions()[source]

Renders the actions specified in Meta.table_actions.

sanitize_id(obj_id)[source]

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

set_multiselect_column_visibility(visible=True)[source]

hide checkbox column if no current table action is allowed.

slugify_name()[source]
take_action(action_name, obj_id=None, obj_ids=None)[source]

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.

class horizon.tables.base.DataTableMetaclass[source]

Bases: type

Metaclass to add options to DataTable class and collect columns.

class horizon.tables.base.DataTableOptions(options)[source]

Bases: object

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.

table_actions_menu

A list of action classes similar to table_actions except these will be displayed in a menu instead of as individual buttons. Actions from this list will take precedence over actions from the table_actions list.

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".

prev_pagination_param

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

pagination_param

The name of the query string parameter which will be used when paginating forward in 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.

css_classes

A custom CSS class or classes to add to the <table> tag of the rendered table, for when the particular table requires special styling. Default: "".

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.

hidden_title

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

permissions

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

class horizon.tables.base.Row(table, datum=None)[source]

Bases: horizon.utils.html.HTMLElement

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 OrderedDict object. This attribute is populated during instantiation.

status[source]

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

status_class[source]

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".

ajax = False
ajax_action_name = 'row_update'
ajax_cell_action_name = 'cell_update'
can_be_selected(datum)[source]

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

get_ajax_update_url()[source]
get_cells()[source]

Returns the bound cells for this row in order.

get_data(request, obj_id)[source]

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)[source]

Load the row’s data (either provided at initialization or as an argument to this function), initialize 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.

render()[source]
status[source]
status_class[source]

Previous topic

The horizon.tables.actions Module

Next topic

The horizon.browsers.breadcrumb Module

Project Source

This Page