Filter-By Category

Example Overview

This example creates dependent dropdowns where selecting a “Main Category” filters the available “Subcategories” through the filter_by parameter, with subcategories loading only once a parent (root) category is chosen. It pairs filtering with metadata-rich dropdowns via PluginDropdownHeader, making it a good fit for hierarchical selections such as content taxonomies or multi-level product filters.

Visual Examples

Screenshot: Filter-By Category

Key Code Segments

Forms

The form uses TomSelectModelChoiceField and TomSelectModelMultipleChoiceField for main categories and subcategories, respectively. The subcategories field is configured with the filter_by parameter.

Explanation:

  • The filter_by parameter dynamically restricts the subcategory options to those associated with the selected main category.

  • The PluginDropdownHeader plugin enriches the UI with additional metadata for categories.

  • The PluginRemoveButton plugin allows users to quickly remove all selected subcategories at once.

Templates

The template filter_by_category.html renders the form and highlights the cascading behavior of the dropdowns.

Autocomplete Views

autocomplete-category provides data for both dropdowns. The backend logic ensures that subcategories are filtered based on the selected main category.

A few key points:

  • We override the hook_queryset method to annotate the queryset with parent information and article counts (see the manager method with_header_data).

  • The hook_prepare_results method formats the results with hierarchy information and additional metadata.

  • We enhance the search method to look through the full hierarchy, including category names, parent names, and full hierarchical paths.

As with most of the example app examples, we set skip_authorization = True to bypass the default authorization checks for simplicity.

See the Article List and Create example for a more comprehensive demonstration, which includes this functionality.