Filter-By Magazine

Example Overview

  • Objective: This example demonstrates how to create dependent dropdowns using django_tomselect. The goal is to filter available options in the “Edition” dropdown based on the selected “Magazine.” If not magazine is selected, the “Edition” dropdown remains empty. If a magazine is selected, the “Edition” dropdown will only show editions linked to that magazine.

    • Problem Solved: Dynamically linking fields avoids presenting users with irrelevant or overwhelming options.

    • Features Highlighted:

      • Dynamic filtering of options using the filter_by parameter.

  • Use Case:

    • Publishing systems where editions are linked to specific magazines.

    • Applications needing cascaded or conditional dropdown menus, such as location selectors or product configurations.

    • User interfaces requiring a clean and intuitive way to manage interdependent fields.

Visual Examples

Screenshot: Filter-By Magazine

Key Code Segments

Forms

This example uses TomSelectModelChoiceField for both magazine and edition fields in the form. The edition field is configured with the filter_by parameter to ensure it depends on the magazine selection.

Explanation:

  • The filter_by parameter in the edition field dynamically narrows down options based on the magazine_id of the selected magazine.

Templates

The form is rendered in the filter_by_magazine.html template, which extends a base template with Bootstrap 5 integration. The extra_header block includes the form media and custom CSS for styling the help text.

Key Elements:

  • Uses Bootstrap 5 for consistent styling.

  • Dynamically displays dropdown options using JavaScript integration with django_tomselect.

Autocomplete Views

autocomplete-magazine and autocomplete-edition endpoints provide data for the dropdowns. These endpoints are backed by models and use filter_by logic to narrow results for the dependent field.

Note that we use skip_authorization = True to bypass the default authorization checks for simplicity in this example.

Dependencies

  • Models: Magazine and Edition models must have a foreign key relationship to enable filtering.

  • URLs: Autocomplete views must be registered in the URL configuration.

Design and Implementation Notes

  • Key Features:

    • Dependency management through filter_by.

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