View Range-based Data

Example Overview

This example pairs a TomSelectChoiceField range selector with an HTMX-driven live preview: selecting a word-count range instantly redraws a bar chart of how many articles fall in each sub-bin (the selected range is broken into 10-word bins), all without a page reload. Use this pattern for interactive filtering and visualization - analytics dashboards, price or date-range filters, or any UI where users explore data distributions by selecting a range.

Visual Examples

Screenshot: View Range-based Data Initial Display Screenshot: View Range-based Data Specific Page Count Bin

Key Code Segments

Forms

The form uses TomSelectChoiceField to allow users to select a range dynamically.

Explanation:

  • The word_count field is configured with a TomSelectConfig object that connects to an autocomplete endpoint and allows range selection.

  • The highlight parameter ensures the selected range is visually prominent.

Templates

The form is rendered in the range_preview.html template, where HTMX is used to update the preview dynamically based on the selected range.

We load the preview container with the initial data on page load and update it when the selected range changes. The range_preview_bars.html template is included in the preview container to display the data visualization.

HTMX Endpoint for Preview Updates

The update-range-preview endpoint processes the selected range and returns the updated data visualization. It uses the get_detailed_range_statistics function to calculate the distribution within the selected range. If no range is selected, it displays the overall distribution.

The get_range_statistics function calculates the distribution for predefined range bins. The range_preview_demo view renders the initial form, and update_range_preview updates the visualization based on the selected range.

Autocomplete Views

The autocomplete-page-count-range endpoint serves the dropdown options for word count ranges.

The WordCountRangeAutocompleteView class extends AutocompleteIterablesView to provide labeled options with counts for each range. It fetches the statistics using the get_range_statistics function, overriding the get_iterable method to return the formatted range options.

Implementation Notes

  • The autocomplete view’s get_iterable override turns each range tuple into a labeled option carrying its live article count, so the dropdown labels stay in sync with the data.

  • get_detailed_range_statistics bins the selected range into fixed-size sub-ranges (default 10 words) to drive the detailed preview; with no range selected, get_range_statistics returns the overall per-range distribution instead.