djblets.datagrid.grids¶
Components for creating customizable datagrids from database data.
Datagrids are used to display a table-based view of data from a database, complete with pagination, batch selection, sorting, and flexible column rendering.
Datagrids have one or more Column
subclasses associated, which will
render the data. The datagrid may display a subset of the rendered columns,
and users can choose which of those columns they want displayed, and in which
order.
There are two main types of datagrids:
DataGrid
is the base class for a datagrid, and will display the data with standard numerical page-based pagination.AlphanumericDataGrid
is similar, but uses a more specific paginator that allows the user to paginate by the first letter/number/symbol of the data in a given field. This is useful for lists of users, for example.
All datagrids are meant to be subclassed.
- class DataGridPaginator(*, total_count: int, **kwargs)¶
Bases:
Paginator
The default paginator used for datagrids.
This is a specialized paginator that takes in a total count separately from the page data queryset. This allows the datagrid code to more efficiently calculate pagination data.
New in version 3.4.
- __annotations__ = {'_total_count': 'int'}¶
- class Column(label: Optional[StrOrPromise] = None, id: Optional[str] = None, detailed_label: Optional[StrOrPromise] = None, detailed_label_html: Optional[str] = None, field_name: Optional[str] = None, db_field: Optional[str] = None, image_url: Optional[str] = None, image_class: Optional[str] = None, image_width: Optional[int] = None, image_height: Optional[int] = None, image_alt: Optional[str] = '', shrink: bool = False, expand: bool = False, sortable: bool = False, default_sort_dir: int = 0, link: bool = False, link_func: Optional[LinkObjectFunc] = None, link_css_class: Optional[Union[str, LinkCSSClassFunc]] = None, cell_clickable: bool = False, css_class: Union[str, BuildCSSClassFunc] = '')¶
Bases:
object
A column in a datagrid.
The column is the primary component of the datagrid. It is used to display not only the column header but the HTML for the cell as well.
Columns can be tied to database fields and can be used for sorting. Not all columns have to allow for this, though.
Columns can have an image, text, or both in the column header. The contents of the cells can be instructed to link to the object on the row or the data in the cell.
If a Column defines an
image_class
, then it will be assumed that the class represents an icon, perhaps as part of a spritesheet, and will display it in a<div>
. Animage_url
cannot also be defined.- __init__(label: Optional[StrOrPromise] = None, id: Optional[str] = None, detailed_label: Optional[StrOrPromise] = None, detailed_label_html: Optional[str] = None, field_name: Optional[str] = None, db_field: Optional[str] = None, image_url: Optional[str] = None, image_class: Optional[str] = None, image_width: Optional[int] = None, image_height: Optional[int] = None, image_alt: Optional[str] = '', shrink: bool = False, expand: bool = False, sortable: bool = False, default_sort_dir: int = 0, link: bool = False, link_func: Optional[LinkObjectFunc] = None, link_css_class: Optional[Union[str, LinkCSSClassFunc]] = None, cell_clickable: bool = False, css_class: Union[str, BuildCSSClassFunc] = '') None ¶
Initialize the column.
When initializing a column as part of a
DataGrid
subclass, a number of options can be provided.- Parameters:
id (
str
, optional) –The unique ID of the column on the datagrid.
if not provided, one will be calculated.
label (
str
, optional) – The label to show in the column header.detailed_label (
str
, optional) – A detailed label to display in the column customization menu. Defaults tolabel
.detailed_label_html (
str
, optional) – A detailed label in HTML form to display in the column customization menu. This takes precedence overdetailed_label
.field_name (
str
, optional) – The name of the field on the model containing the data to render.db_field (
str
, optional) – The name of the database field containing the field used for sorting. Defaults tofield_name
.image_url (
str
, optional) – The URL to the image used in the header and navigation menu. This cannot be used withimage_class
.image_class (
str
, optional) – The CSS class of a spritesheet icon to use in the header and navigation menu. This cannot be used withimage_url
.image_width (
int
, optional) – The width of the image.image_height (
int
, optional) – The height of the image.image_alt (
str
, optional) – The alt text for the image.shrink (
bool
, optional) – IfTrue
, the column’s width will be calculated to its minimum size.expand (
bool
, optional) – IfTrue
, the column’s width will be calculated to its maximum size. If there are other expanded columns, they’ll share the available width equally.sortable (
bool
, optional) – IfTrue
, the column can be sorted. This requires adb_field
that allows for sorting.default_sort_dir (
int
, optional) – The default sorting direction when the user activates sorting. EitherSORT_DESCENDING
orSORT_ASCENDING
.link (
bool
, optional) – IfTrue
, the contents will be linked to the URL returned bylink_func
orDataGrid.link_to_object()
.link_func (
callable
, optional) – Optional function that returns a URL for the link.link_css_class (
str
orcallable
, optional) – The CSS class or classes to define on<a>
for the link for the cell, if settinglink=True
. This can be a function returning the classes.cell_clickable (
bool
, optional) – IfTrue
, clicking anywhere on the cell will navigate to the URL defined, if any.css_class (
str
orcallable
, optional) –The CSS class or classes to define on the cell.
This can be a function returning the classes.
- field_name: str¶
The name of the field on the model containing the data to render.
Once columns are populated for a datagrid, this is guaranteed to be set.
- Type:
- db_field: str¶
The name of the database field containing the field used for sorting.
Once columns are populated for a datagrid, this is guaranteed to be set.
- Type:
- detailed_label: Optional[StrOrPromise]¶
A detailed label to display in the Edit Columns menu.
Defaults to
label
.- Type:
- detailed_label_html: Optional[StrOrPromise]¶
A detailed label in HTML form to display in the Edit Columns menu.
This takes precedence over
detailed_label
.- Type:
- image_class: Optional[str]¶
The CSS spritesheet icon class to use in the header/navigation menu.
- Type:
- expand: bool¶
Whether the column will expand to the maximum size allowed.
If there are other expanded columns, they’ll share the available width equally.
- Type:
- default_sort_dir: int¶
The default sorting direction when the user activates sorting.
This must be either
SORT_ASCENDING
orSORT_DESCENDING
.- Type:
- cell_clickable: bool¶
Whether clicking anywhere on the cell should navigate to a defined link.
This can be set to distinguish between a cell that links to an object versus a cell that contains a link to an object.
This is only used if
link
isTrue
.- Type:
- link: bool¶
Whether the contents of the cell will be linked to a URL.
The URL used must be defined by either
link_func
orDataGrid.link_to_object()
.- Type:
- link_func: LinkObjectFunc¶
A function used to return a URL for a given object.
This is only used if
link
isTrue
.- Type:
callable
- link_css_class: Optional[Union[str, LinkCSSClassFunc]]¶
A function or string for CSS classes applied to a link.
The CSS classes will be defined on the
<a>
for the cell’s link wrapper. This is only used iflink
isTrue
.- Type:
str
orcallable
- css_class: Union[str, BuildCSSClassFunc]¶
A function or string for CSS classes applied to the cell.
- Type:
str
orcallable
- cell_template: Optional[str]¶
The path to a template for the cell.
If provided, this will override the
DataGrid.cell_template
in the parent DataGrid.- Type:
- cell_template_obj¶
Return the cell template, if it exists.
By default, this requires
cell_template
to be set.- Returns:
The template backend-specific template for the cell.
- Return type:
- setup_state(state: StatefulColumn) None ¶
Set up any state that may be needed for the column.
This is called once per column per datagrid instance.
By default, no additional state is set up. Subclasses can override this to set any variables they may need.
- Parameters:
state (
StatefulColumn
) – The state for the DataGrid instance.
- get_sort_field(state: StatefulColumn) Optional[str] ¶
Return the field used for sorting this column.
By default, this returns
db_field
.- Parameters:
state (
StatefulColumn
) – The state for the DataGrid instance.- Returns:
The field on the model used for sorting.
- Return type:
- get_toggle_url(state: StatefulColumn) str ¶
Return a URL to toggle this column’s visibility.
- Parameters:
state (
StatefulColumn
) – The state for the DataGrid instance.- Returns:
The URL used to toggle column visibility.
- Return type:
- get_header(state: StatefulColumn) str ¶
Render the header for the column.
The column header will include the current sort indicator, if it belongs in the sort list. It will also be made clickable in order to modify the sort order appropriately, if sortable.
- Parameters:
state (
StatefulColumn
) – The state for the DataGrid instance.- Returns:
The HTML for the header.
- Return type:
- collect_objects(state: StatefulColumn, object_list: Iterable[Any]) None ¶
Iterate through the objects and builds a cache of data to display.
This optimizes the fetching of data in the grid by grabbing all the IDs of related objects that will be queried for rendering, loading them all at once, and populating the cache.
- Parameters:
state (
StatefulColumn
) – The state for the DataGrid instance.object_list (
list
) – The list of objects being rendered on the datagrid.
- render_cell(state: StatefulColumn, obj: Any, render_context: _RenderContext) str ¶
Render the table cell containing column data.
- Parameters:
state (
StatefulColumn
) – The state for the DataGrid instance.obj (
object
) – The object being rendered for this row.render_context (
dict
ordjango.template.context.Context
) – The shared context used for cell renders.
- Returns:
The rendered cell as HTML.
- Return type:
- render_data(state: StatefulColumn, obj: Any) str ¶
Render the column data within the cell.
- Parameters:
state (
StatefulColumn
) – The state for the DataGrid instance.obj (
object
) – The object being rendered for this row.
- Returns:
The rendered data as HTML.
- Return type:
- augment_queryset_for_filter(state: StatefulColumn, queryset: QuerySet, *, request: HttpRequest, **kwargs) QuerySet ¶
Augment a queryset for filtering purposes.
Subclasses can override this to add filters to the queryset to limit the results returned for display and for pagination.
This must not be used to load additional data for display, or to pre-fetch/select-related any columns, unless required as part of the filter. Instead, override
augment_queryset_for_data()
.New in version 3.4.
- Parameters:
state (
StatefulColumn
) – The state for the DataGrid instance.queryset (
django.db.models.query.QuerySet
) – The queryset to augment.request (
django.http.HttpRequest
) – The HTTP request from the client.**kwargs (
dict
) – Additional keyword arguments for future expansion.
- Returns:
The resulting augmented QuerySet.
- Return type:
- augment_queryset_for_data(state: StatefulColumn, queryset: QuerySet, *, request: HttpRequest, **kwargs) QuerySet ¶
Augment a queryset for data-rendering purposes.
Subclasses can override this to query for additional data used for displaying this column.
This must not be used to filter querysets. Instead, override
augment_queryset_for_filter()
.New in version 3.4.
- Parameters:
state (
StatefulColumn
) – The state for the DataGrid instance.queryset (
django.db.models.query.QuerySet
) – The queryset to augment.request (
django.http.HttpRequest
) – The HTTP request from the client.**kwargs (
dict
) – Additional keyword arguments for future expansion.
- Returns:
The resulting augmented QuerySet.
- Return type:
- augment_queryset(state: StatefulColumn, queryset: QuerySet) QuerySet ¶
Augment a queryset with new queries.
Subclasses can override this to extend the queryset to provide additional information, usually using queryset.extra(). This must return a queryset based on the original queryset.
This should not restrict the query in any way, or the datagrid may not operate properly. It must only add additional data to the queryset.
- Parameters:
state (
StatefulColumn
) – The state for the DataGrid instance.queryset (
django.db.models.QuerySet
) – The queryset to augment.
- Returns:
The resulting QuerySet.
- Return type:
django.db.models.QuerySet
- __annotations__ = {'SORT_ASCENDING': 'Final[int]', 'SORT_DESCENDING': 'Final[int]', 'cell_clickable': 'bool', 'cell_template': 'Optional[str]', 'css_class': 'Union[str, BuildCSSClassFunc]', 'db_field': 'str', 'default_sort_dir': 'int', 'detailed_label': 'Optional[StrOrPromise]', 'detailed_label_html': 'Optional[StrOrPromise]', 'expand': 'bool', 'field_name': 'str', 'id': 'str', 'image_alt': 'Optional[str]', 'image_class': 'Optional[str]', 'image_height': 'Optional[int]', 'image_url': 'Optional[str]', 'image_width': 'Optional[int]', 'label': 'Optional[StrOrPromise]', 'link': 'bool', 'link_css_class': 'Optional[Union[str, LinkCSSClassFunc]]', 'link_func': 'LinkObjectFunc', 'shrink': 'bool', 'sortable': 'bool'}¶
- class StatefulColumn(datagrid: DataGrid, column: Column)¶
Bases:
object
A stateful wrapper for a Column instance.
Columns must be stateless, as they are shared across all instances of a particular DataGrid. However, some state is needed for columns, such as their widths or active status.
StatefulColumn wraps a
Column
instance and provides state storage, and also provides a convenient way to call methods on a Column and pass the state.Attributes owned by the Column can be accessed directly through the StatefulColumn.
Likewise, any functions owned by the Column can be accessed as well. The function will be invoked with this StatefulColumn as the first parameter passed.
- property toggle_url: str¶
The visibility toggle URL of the column.
This is a convenience used by templates to call
Column.get_toggle_url()
with the current state.- Type:
- property header: str¶
The header of the column.
This is a convenience used by templates to call
Column.get_header()
with the current state.- Type:
- __getattr__(name: str) Any ¶
Returns an attribute from the parent Column.
This is called when accessing an attribute not found directly on StatefulColumn. The attribute will be fetched from the Column (if it exists there).
In the case of accessing a function, a wrapper will be returned that will automatically pass this StatefulColumn instance as the first parameter.
- __annotations__ = {'active': 'bool', 'cell_render_cache': 'Dict[str, str]', 'column': 'Column', 'data_cache': 'Dict[Any, Any]', 'datagrid': 'DataGrid', 'last': 'bool', 'width': 'float'}¶
- class CheckboxColumn(checkbox_name: str = 'select', shrink: bool = True, show_checkbox_header: bool = True, detailed_label: Optional[StrOrPromise] = 'Select Rows', *args, **kwargs)¶
Bases:
Column
A column that renders a checkbox.
The
is_selectable()
andis_selected()
functions can be overridden to control whether a checkbox is displayed in a row and whether that checkbox is initially checked.The checkboxes have a
data-object-id
attribute that contains the ID of the object that row represents. This allows the JavaScript code to determine which rows have been checked, and operate on that accordingly.The checkboxes also have a
data-checkbox-name
attribute that contains the value passed in to thecheckbox_name
parameter of its constructor.- __init__(checkbox_name: str = 'select', shrink: bool = True, show_checkbox_header: bool = True, detailed_label: Optional[StrOrPromise] = 'Select Rows', *args, **kwargs) None ¶
Initialize the column.
- Parameters:
checkbox_name (
str
) – The name set indata-checkbox-name
.shrink (
bool
) – IfTrue
, the column’s width will be calculated to its minimum size.show_checkbox_header (
bool
) – IfTrue
, a checkbox will be used for the column header.detailed_label (
str
, optional) – The detailed label to show for the column.*args (
tuple
) – Additional positional arguments for the column.**kwargs (
dict
) – Additional keyword arguments for the column.
- checkbox_name: str¶
The name to set for the checkbox in the HTML.
This is set in
data-checkbox-name
.- Type:
- render_data(state: StatefulColumn, obj: Any) str ¶
Render the column data within the cell.
- Parameters:
state (
StatefulColumn
) – The state for the DataGrid instance.obj (
object
) – The object being rendered for this row.
- Returns:
The rendered data as HTML.
- Return type:
- is_selectable(state: StatefulColumn, obj: Any) bool ¶
Return whether an object can be selected.
By default, this always returns
True
. Subclasses can override this to disable rendering a checkbox for a given object.- Parameters:
state (
StatefulColumn
) – The state for the DataGrid instance.obj (
object
) – The object being rendered for this row.
- Returns:
True
if a checkbox will be rendered and can be selected.False
if no checkbox will be rendered.- Return type:
- is_selected(state: StatefulColumn, obj: Any) bool ¶
Return whether an object is selected by default.
By default, this returns
False
. Subclasses can override this to enable a checkbox by default for a given object.- Parameters:
state (
StatefulColumn
) – The state for the DataGrid instance.obj (
object
) – The object being rendered for this row.
- Returns:
True
if the checkbox will be selected by default.False
if it will not.- Return type:
- __annotations__ = {'SORT_ASCENDING': 'Final[int]', 'SORT_DESCENDING': 'Final[int]', 'cell_clickable': 'bool', 'cell_template': 'Optional[str]', 'checkbox_name': 'str', 'css_class': 'Union[str, BuildCSSClassFunc]', 'db_field': 'str', 'default_sort_dir': 'int', 'detailed_label': 'Optional[StrOrPromise]', 'detailed_label_html': 'Optional[StrOrPromise]', 'expand': 'bool', 'field_name': 'str', 'id': 'str', 'image_alt': 'Optional[str]', 'image_class': 'Optional[str]', 'image_height': 'Optional[int]', 'image_url': 'Optional[str]', 'image_width': 'Optional[int]', 'label': 'Optional[StrOrPromise]', 'link': 'bool', 'link_css_class': 'Optional[Union[str, LinkCSSClassFunc]]', 'link_func': 'LinkObjectFunc', 'show_checkbox_header': 'bool', 'shrink': 'bool', 'sortable': 'bool'}¶
- class DateTimeColumn(label: Optional[StrOrPromise] = None, format: Optional[str] = None, sortable: bool = True, timezone: Any = <UTC>, *args, **kwargs)¶
Bases:
Column
A column that renders a date or time.
- __init__(label: Optional[StrOrPromise] = None, format: Optional[str] = None, sortable: bool = True, timezone: Any = <UTC>, *args, **kwargs) None ¶
Initialize the column.
- Parameters:
label (
str
, optional) – The label to show in the column header.format (
str
, optional) –The format used to show the date/time.
This must be a valid
strftime()
format string. If not provided, Django’s default will be used.sortable (
bool
, optional) –Whether the field should be sortable.
This is enabled by default.
timezone (
object
, optional) – The timezone used to normalize the date/time to.*args (
tuple
) – Additional positional arguments for the column.**kwargs (
dict
) – Additional keyword arguments for the column.
- render_data(state: StatefulColumn, obj: Any) str ¶
Render the column data within the cell.
- Parameters:
state (
StatefulColumn
) – The state for the DataGrid instance.obj (
object
) – The object being rendered for this row.
- Returns:
The rendered data as HTML.
- Return type:
- __annotations__ = {}¶
- class DateTimeSinceColumn(label: Optional[StrOrPromise] = None, sortable: bool = True, *args, **kwargs)¶
Bases:
Column
A column that renders a date or time relative to now.
- __init__(label: Optional[StrOrPromise] = None, sortable: bool = True, *args, **kwargs) None ¶
Initialize the column.
- render_data(state: StatefulColumn, obj: Any) str ¶
Render the column data within the cell.
- Parameters:
state (
StatefulColumn
) – The state for the DataGrid instance.obj (
object
) – The object being rendered for this row.
- Returns:
The rendered data as HTML.
- Return type:
- __annotations__ = {}¶
- class DataGrid(request: HttpRequest, queryset: Optional[QuerySet] = None, title: str = '', extra_context: _RenderContext = {}, optimize_sorts: bool = True, model: Optional[Type[Model]] = None, use_distinct: bool = True)¶
Bases:
object
A paginated table of data based on queries from a database.
A datagriad represents a list of objects, sorted and organized by columns. The sort order and column lists can be customized. allowing users to view this data however they prefer.
This is meant to be subclassed for specific uses. The subclasses are responsible for defining one or more column types. It can also set one or more of the following optional variables:
- custom_header_template: str¶
The template used to render each column header.
The default is
datagrid/column_header.html
.- Type:
- classmethod add_column(column: Column) None ¶
Add a new column for this datagrid.
This can be used to add columns to a DataGrid subclass after the subclass has already been defined.
The column added must have a unique ID already set.
- classmethod remove_column(column: Column) None ¶
Remove a column from this datagrid.
This can be used to remove columns previously added through
add_column()
.
- classmethod get_column(column_id: str) Optional[Column] ¶
Return the column with the given ID.
If not found, this will return None.
- classmethod get_columns() Sequence[Column] ¶
Return the list of registered columns for this datagrid.
- __annotations__ = {'_model': 'Optional[Type[Model]]', 'cell_template': 'str', 'column_map': 'Dict[Column, StatefulColumn]', 'columns': 'List[StatefulColumn]', 'custom_header_template': 'str', 'default_columns': 'List[str]', 'default_sort': 'List[str]', 'extra_context': '_RenderContext', 'id': 'str', 'id_list': 'List[Any]', 'listview_template': 'str', 'optimize_sorts': 'bool', 'page': 'Optional[Page]', 'page_num': 'int', 'paginate_by': 'int', 'paginate_orphans': 'int', 'paginator': 'Optional[DataGridPaginator]', 'paginator_template': 'str', 'profile_columns_field': 'Optional[str]', 'profile_sort_field': 'Optional[str]', 'rows': 'List[_DataGridRow]', 'sort_list': 'Optional[List[str]]', 'special_query_args': 'List[str]', 'state_loaded': 'bool', 'title': 'StrOrPromise', 'use_distinct': 'bool'}¶
- __init__(request: HttpRequest, queryset: Optional[QuerySet] = None, title: str = '', extra_context: _RenderContext = {}, optimize_sorts: bool = True, model: Optional[Type[Model]] = None, use_distinct: bool = True) None ¶
Initialize the datagrid.
Changed in version 3.4: Added the
use_distinct
argument.- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.queryset (
django.db.models.QuerySet
, optional) – A QuerySet returning the objects to render in the grid.title (
str
, optional) – The displayed title of the datagrid.extra_context (
dict
ordjango.template.Context
, optional) – Extra context variables to render on the datagrid template.optimize_sorts (
bool
, optional) – IfTrue
, sorting will be optimized, reducing the complexity of the queries. This is the default.model (
type
, optional) – The model for the objects in the datagrid. Defaults to the model associated withqueryset
.use_distinct (
bool
, optional) –Whether to use distinct querysets.
This is currently enabled by default. This default may be changed in a future release. Callers should explicitly set this to the value they want to use.
New in version 3.4.
- columns: List[StatefulColumn]¶
A list of all stateful columns on this datagrid.
- Type:
- column_map: Dict[Column, StatefulColumn]¶
A mapping of columns to stateful columns.
- Type:
- paginator: Optional[DataGridPaginator]¶
The paginator managing pages of results.
- Type:
- page: Optional[Page]¶
The current page of results.
- page_num: int¶
The 1-based page number to display.
If this is not explicitly set, the
?page=
query argument will be used. Otherwise, this defaults to 1.- Type:
- optimize_sorts: bool¶
Whether or not to optimize queries when using multiple sorts.
This can offer a speed improvement, but may need to be turned off for more advanced querysets (such as when using
QuerySet.extra()
).The default is
True
.- Type:
- use_distinct: bool¶
Whether to use distinct querysets.
This is currently enabled by default. This default may be changed in a future release. Callers should explicitly set this to the value they want to use.
New in version 3.4.
- Type:
- special_query_args: List[str]¶
Query arguments to include when fetching datagrid contents.
- Type:
List[str]
- profile_columns_field: Optional[str]¶
The profile field storing the column list for the datagrid.
- Type:
- paginate_orphans: int¶
The number of orphan items to collect on the last page of results.
If the last page contains this number of objects or fewer, it will be rolled up into the previous page.
- Type:
- listview_template: str¶
The template used to render the list view.
The default is
datagrid/listview.html
.- Type:
- cell_template: str¶
The template used to render a cell of data.
The default is
datagrid/cell.html
.- Type:
- paginator_template: str¶
The template used for the paginator.
This defaults to
datagrid/paginator.html
.- Type:
- cell_template_obj¶
The rendered template used for cells on this datagrid.
This will only be generated once, and reused for all cells.
- Type:
- column_header_template_obj¶
The rendered template used for column headers on this datagrid.
This will only be generated once, and reused for all headers.
- Type:
- property all_columns: Sequence[StatefulColumn]¶
All columns in the datagrid, sorted by label.
- Type:
- property model: Optional[Type[Model]]¶
The model representing the objects shown in the grid.
- Type:
- get_stateful_column(column: Column) StatefulColumn ¶
Return a StatefulColumn for the given Column instance.
If one has already been created, it will be returned.
- Parameters:
column (
Column
) – The column associated with the stateful column.- Returns:
The column state associated with the column.
- Return type:
- load_state(render_context: Optional[_RenderContext] = None) None ¶
Load the state of the datagrid.
This will retrieve the user-specified or previously stored sorting order and columns list, as well as any state a subclass may need.
- Parameters:
render_context (
dict
ordjango.template.Context
, optional) – Common template variable context to render on the datagrid.
- get_user_profile() Optional[Model] ¶
Return the object, if any, to use for the user profile state.
- Returns:
The object, if any, used to store and retrieve persistent profile state for the datagrid.
- Return type:
- load_extra_state(profile: Optional[Model]) Union[bool, List[str]] ¶
Load any extra state needed for this grid.
This is used by subclasses that may have additional data to load and save.
Changed in version 3.0: This should now return a list of field names to save in
profile
. Any other result is deprecated and will no longer be supported in Djblets 4.0.- Parameters:
profile (
django.db.models.Model
) – The profile model instance to load from, if any.- Returns:
A list of field names on
profile
that have been modified and should be saved.Djblets 3.0 and older support
True
to save the entire object, orFalse
if fields weren’t modified. This support will be removed in Djblets 4.0.- Return type:
- precompute_objects(render_context: Optional[_RenderContext] = None) None ¶
Pre-compute all objects used to render the datagrid.
This builds the queryset and stores the list of objects for use in rendering the datagrid. It takes into consideration sorting, the current page, and augmented queries from columns.
- Parameters:
render_context (
dict
ordjango.template.Context
) – The common template variable context to render on the datagrid, provided in the constructor.
- post_process_queryset_for_filter(queryset: QuerySet, **kwargs) QuerySet ¶
Add column-specific filters to the queryset.
Subclasses can override this to add filters to the queryset to limit the results returned for display and for pagination.
This must not be used to load additional data for display, or to pre-fetch/select-related any columns, unless required as part of the filter. Instead, override
post_process_queryset_for_data()
.New in version 3.4.
- Parameters:
queryset (
django.db.models.query.QuerySet
) – The queryset to augment.**kwargs (
dict
) – Additional keyword arguments for future expansion.
- Returns:
The resulting augmented QuerySet.
- Return type:
- post_process_queryset_for_data(queryset: QuerySet, **kwargs) QuerySet ¶
Add column-specific data lookups to the queryset.
Subclasses can override this to query for additional data used for displaying this column.
This must not be used to filter querysets. Instead, override
post_process_queryset_for_filter()
.New in version 3.4.
- Parameters:
queryset (
django.db.models.query.QuerySet
) – The queryset to augment.**kwargs (
dict
) – Additional keyword arguments for future expansion.
- Returns:
The resulting augmented QuerySet.
- Return type:
- post_process_queryset(queryset: QuerySet) QuerySet ¶
Add column-specific data to the queryset.
Individual columns can define additional joins and extra info to add on to the queryset. This handles adding all of those.
- Parameters:
queryset (
django.db.models.query.QuerySet
) – The queryset to augment.- Returns:
The resulting augmented QuerySet.
- Return type:
- render_listview(render_context: Optional[_RenderContext] = None) SafeString ¶
Render the standard list view of the grid.
This can be called from templates.
- Parameters:
render_context (
dict
ordjango.template.Context
, optional) – The common template variable context to render on the datagrid, provided in the constructor.- Returns:
The rendered HTML for the datagrid page.
- Return type:
- render_listview_to_response(request: Optional[HttpRequest] = None, render_context: Optional[_RenderContext] = None) HttpResponse ¶
Render the listview to a response.
The rendered result will not be cached by the browser.
- Parameters:
request (
django.http.HttpRequest
, optional) – The HTTP request from the client.render_context (
dict
ordjango.template.Context
, optional) – The common template variable context to render on the datagrid, provided in the constructor.
- Returns:
The HTTP response to send to the client.
- Return type:
- render_to_response(template_name: str, extra_context: _RenderContext = {}) HttpResponse ¶
Render the entire datagrid page to a response.
This will render the entire page, given the specified template, with the datagrid as a part of it. This is the primary function a view will be using to render the page.
- Parameters:
template_name (
str
) – The template for the page.extra_context (
dict
ordjango.template.Context
) – Extra context variables to use in the template.
- Returns:
The HTTP response to send to the client.
- Return type:
- render_paginator(adjacent_pages: int = 3) SafeString ¶
Render the paginator for the datagrid.
This can be called from templates.
- Parameters:
adjacent_pages (
int
) – The number of adjacent page numbers to show in the paginator.- Returns:
The paginator as HTML.
- Return type:
- build_paginator(queryset: QuerySet, *, total_count: int, **kwargs) DataGridPaginator ¶
Build the paginator for the datagrid.
This can be overridden to use a special paginator or to perform any kind of processing before passing on the query.
- static link_to_object(state: StatefulColumn, obj: Any, value: Any) str ¶
Return a URL for the given object.
This defaults to calling
obj.get_absolute_url
.- Returns:
The URL for the object.
- Return type:
- class AlphanumericDataGrid(request: HttpRequest, queryset: QuerySet, sortable_column: str, extra_regex: str = '^[0-9].*', *args, **kwargs)¶
Bases:
DataGrid
A DataGrid subclass for an alphanumerically-paginated datagrid.
This is useful for datasets that need to be queried alphanumerically, according to the starting character of their
sortable
column.- __annotations__ = {'current_letter': 'str'}¶
- __init__(request: HttpRequest, queryset: QuerySet, sortable_column: str, extra_regex: str = '^[0-9].*', *args, **kwargs) None ¶
Initialize the datagrid.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.queryset (
django.db.models.QuerySet
) – A QuerySet returning the objects to render in the grid.sortable_column (
str
) – The model field used for the alphanumeric prefixes.extra_regex (
str
, optional) – A regex used for matching the beginning of entries insortable_column
.*args (
tuple
) – Positional arguments to pass to the parent constructor.**kwargs (
dict
) – Keyword arguments to pass to the parent constructor.
- LinkObjectFunc¶
A type alias for a function that returns a URL for an object.
New in version 3.4.
alias of
Callable
[[StatefulColumn
,Any
,str
],str
]
- LinkCSSClassFunc¶
A type alias for a function that returns a CSS class name for a link.
New in version 3.4.