Skip to main content

Workspace components

Added in 1.0.23

Use workspace components to display prepared values in a custom Admin page, a ModelAdmin template or a dashboard card. Each component is a frozen dataclass with a fixed template. The project collects the data, applies permissions and removes secrets before it constructs the DTO.

For rendered examples, see the dashboard demo and the ModelAdmin demo.

Render a component​

Put a workspace DTO in your view's context. The chassis_component tag renders its template_name with that DTO as component, using Django template escaping. For Python rendering, import render_component from django_chassis.renderers.component. Both entry points return HTML with the same validation. Pass ordinary text as strings. Guard optional components with {% if %} before calling the tag.

This example builds a readiness header and a pair of catalog counts. Add CatalogHealthPage to your Chassis AdminSite's chassis_page_classes.

from django.utils import timezone

from django_chassis.dto import (
AdminInformationRowDTO,
ContextBarDTO,
MetricSummaryDTO,
SummaryStripDTO,
SummaryStripItemDTO
)
from django_chassis.enums import DisplayState
from django_chassis.views import SuperuserAdminPage


class CatalogHealthPage(SuperuserAdminPage):
slug = 'catalog-health'
title = label = 'Catalog health'
template_name = 'catalog/admin/health.html'

def view(self, request):
observed_at = timezone.now()
return self.render(
request,
header=ContextBarDTO(
title='Catalog',
state=DisplayState.NORMAL,
facts=(AdminInformationRowDTO('Source', 'Primary catalog'),)
),
totals=SummaryStripDTO(items=(
SummaryStripItemDTO(MetricSummaryDTO('Listed products', 325, observed_at=observed_at)),
SummaryStripItemDTO(MetricSummaryDTO('Missing images', 0, observed_at=observed_at))
))
)

Save the template as templates/catalog/admin/health.html. With a site mounted at /admin/, an active staff superuser can open /admin/pages/catalog-health/. Both counts render, including the measured zero. Replace the sample counts with observations the requesting user can see.

{% extends "admin/chassis/page.html" %}
{% load static chassis_component %}

{% block extrastyle %}
{{ block.super }}
<link rel="stylesheet" href="{% static 'admin/chassis/workspace_components.css' %}">
{% endblock %}

{% block chassis_page_content %}
{% chassis_component header %}
{% chassis_component totals %}
{% endblock %}

Actions and assets​

Use AdminPageActionDTO(label=..., url=..., color=...) for navigation links. The renderer checks these actions recursively within dataclasses, lists and tuples. It accepts HTTP(S) URLs and relative URLs that begin with /, # or ?. It raises ValueError for executable schemes, protocol-relative URLs, backslashes and control characters. Use Django reverse() for internal links. The target view must still authorize the request. Supply trusted URLs for other URL fields such as illustration_url, and use a permission-checked POST form for operations that change data.

On a custom Chassis Admin page, add workspace_components.css as above and load only the scripts used by the page. Paths below are relative to admin/chassis/ in static storage.

BehaviorAssets
Render a chart in a metric or share cardapexcharts/apexcharts.css, apexcharts/apexcharts.min.js, then dashboard_charts.js. Add dashboard.css for the dashboard's chart layout.
Switch diff layout, copy either side and unfold contextcode_diff.js. The original side-by-side table is server-rendered.
Search, filter and follow the full log bufferlog_viewer.js. Search applies to loaded entries.
Refresh a project-owned HTML fragmentlive_toolbar.js. Add live_fragment_charts.js if the fragment contains chart markup, and mark its target with data-chassis-live-charts.
Refresh the built-in dashboardThe dashboard template loads dashboard_live.js and its chart assets. It loads the workspace stylesheet for cards or the toolbar, and the workspace scripts when data cards are visible.

Orientation and navigation​

All DTOs in the tables can be imported from django_chassis.dto. Use DisplayState from django_chassis.enums for a semantic status. Its values are NORMAL, WARNING, ERROR, UNKNOWN, STALE, LOADING and PAUSED.

ComponentInputs and behavior
ContextBarDTOtitle, state, a tuple of facts, optional description and action. Use above metrics to identify the data source or scope.
OverviewCardDTOtitle, description, up to three MetricSummaryDTO facts and four navigation actions, optional badge and illustration_url. Facts can show goal progress.
EntitySummaryDTOtitle, subtitle, facts and optional state. Use for the identity and essential properties of one object.
CategoryNavigationDTOtitle and items of CategoryNavigationItemDTO(action, count=None, active=False). Pass the selected category and its count from the view.
ResourceCollectionDTOtitle, items of ResourceItemDTO, layout, limit, empty_message, optional all_action for compact lists. Items have title, optional subtitle, facts, action, status_label and state. grid renders all items in supplied order. compact, ranking, recent and attention display at most limit items (1–10). Sort or filter before passing the list.
RelationFlowDTOtitle and nodes of AdminInformationRowDTO. The first five appear in order.
RichValueCellDTOprimary, optional secondary, unit, action, state, icon_class and badges. Render in a cell of a custom table.
EmptyStateDTOtitle, optional description and action. The template shows a plain status message and link.

Facts and nodes use AdminInformationRowDTO(label, value, ...). Individual templates can use a subset of the row's optional fields. See Information pages for rows, badges and timelines.

Metrics, shares and goals​

ComponentInputs and behavior
MetricSummaryDTOtitle, value, optional unit, state, observed_at, description, action and breakdown. Use value_format of number, money, percent or duration. Duration takes seconds. Percent takes a percentage value, such as 25 for 25%. For money, specify the currency with unit. decimal_places ranges from 0 to 12. None displays an em dash. Use a number to calculate a delta against previous_value; a zero baseline yields no relative delta. positive_is_good controls delta color, comparison_label sets the comparison label, and show_state controls whether status appears. Supply an optional DashboardChartDTO and chart_height of 24–600 pixels for a trend.
SummaryStripDTOAn items tuple of SummaryStripItemDTO(metric, icon_class='', badges=()). Displays each metric's compact value, state and link together.
GoalSummaryDTOtitle, actual, target as Decimal or None, and optional unit, deadline, description, mode and lower_is_better. The deadline must be timezone-aware. mode='quota' uses the danger color for overage. A missing or nonpositive target leaves the percentage unknown. The progress bar clamps at 100% while the actual percentage and remaining quantity retain their values.
ShareSummaryDTOtitle, slug, definition, numerator, denominator, optional labels and links for numerator and remainder, variant='radial' or 'donut', and is_compact. Use finite, nonnegative Decimal values with numerator ≤ denominator, or None for missing values. The chart and legend use the same counts. A zero or missing denominator leaves the share unknown. Give every chart on the page a distinct slug.

For example, count products with a current image and show the result next to the weekly upload goal. Pass each DTO to the template or wrap it in DashboardCardDTO(content=..., ...).

from decimal import Decimal

from django_chassis.dto import GoalSummaryDTO, ShareSummaryDTO

image_coverage = ShareSummaryDTO(
title='Image coverage',
slug='catalog-images',
definition='Listed products with a current image',
numerator=Decimal(312),
denominator=Decimal(325),
numerator_label='Current image',
remainder_label='Missing or outdated'
)
upload_goal = GoalSummaryDTO(
title='Weekly upload goal',
actual=Decimal(52),
target=Decimal(50),
unit='images'
)

Operations and status​

ComponentInputs and behavior
StatusStripDTOtitle, state, optional checked_at, description and action. Shows an observation and the time it was checked.
SecuritySummaryDTOtitle, state, facts, description and navigation actions. Supply the latest known policy or access facts from the application.
AttentionListDTOtitle, items of AdminInformationRowDTO, and empty_message. Use for a prepared list of issues.
OperationTrackerDTOtitle, status_label, state, optional step_label, updated_at, actions, waiting_count, running_count, failed_count, processed and total. Counts must be nonnegative. Progress appears when processed and a positive total are known.
AvailabilityHistoryDTOtitle, samples, optional percentage, coverage_percentage, period_label, timezone_label, paired period bounds, compact and density (mini, card, detail). The project supplies the percentages from 0 to 100. The timeline renders only the last 200 supplied samples and marks truncation.
AvailabilitySampleDTOChild of AvailabilityHistoryDTO, with label and state of up, down or unknown, plus optional observed_at, action and reason. For intervals, give both started_at and ended_at as timezone-aware values in ascending order. Intervals must be ordered, nonoverlapping and inside the declared period bounds when present.

Logs and comparisons​

ComponentInputs and behavior
LogViewerDTOtitle and entries of LogEntryDTO. Full mode renders the last limit entries in supplied order (default 200). Add source_label, sources, and optional previous_action, next_action and export_action for server-side navigation. is_summary=True shows the five newest entries, deduplicates by nonempty source/reference, and can drop info entries with attention_only=True. Use all_action for a link to the full journal.
LogEntryDTOChild of LogViewerDTO, with timestamp, message, level of info, warning or error, and optional reference, details, source, object_label and action. With use_inspector=True the summary link also carries an inspector data attribute. The destination link must work as ordinary navigation.
FieldChangeListDTOtitle, fields of FieldChangeDTO, optional before_label, after_label, author and changed_at. Set is_comparable=False when there is no comparable snapshot.
FieldChangeDTOChild of FieldChangeListDTO, with label, before, after, optional key and diff. A change of type counts as a difference, such as False to 0.
CodeDiffViewerDTOtitle, lines of CodeDiffLineDTO, optional side labels and is_truncated. Each line has before, after, kind (context, added, removed, changed) and optional 1-based line numbers.

Use CodeDiffService.build() to turn two authorized texts into a diff. It limits input to 1,000,000 characters per side and produces at most limit lines (default 1,000). For ModelAdmin history, see field comparisons.

from django_chassis.dto import FieldChangeDTO, FieldChangeListDTO
from django_chassis.services.code_diff_service import CodeDiffService

before = '{"items_per_page": 25}'
after = '{"items_per_page": 50}'
history = FieldChangeListDTO(
title='Catalog settings',
fields=[
FieldChangeDTO(
label='Paging options',
key='catalog.pagination',
before=before,
after=after,
diff=CodeDiffService.build(title='Paging options', before=before, after=after)
)
]
)

Live refresh​

LiveToolbarDTO(target_id, endpoint_url, ...) renders pause and refresh controls. Give it a simple DOM ID and a same-origin absolute path or query. The interval is interval_seconds (default 30, positive). Set observed_at, fetched_at, timezone_label and is_paused when those values are known.

For a custom page, put the toolbar outside the DOM element it refreshes. Load live_toolbar.js and provide a protected GET endpoint. The script sends X-Chassis-Live: 1. Return rendered inner HTML with X-Chassis-Live-Fragment: 1, or HTTP 304 when appropriate. On a failed response, the last rendered result stays visible. The endpoint must authorize and filter each response. On the built-in dashboard, Chassis generates a toolbar with uses_dashboard_cycle=True and uses its separate dashboard refresh endpoint.

For example, pass LiveToolbarDTO(target_id='catalog-observations', endpoint_url='?fragment=1') as toolbar and an OperationTrackerDTO as progress to a dashboard-adjacent page. Have the protected fragment response render only the progress tag.

{% load chassis_component %}
{% chassis_component toolbar %}
<div id="catalog-observations">
{% chassis_component progress %}
</div>