Filter-By Magazine

Example Overview

This example builds a pair of dependent dropdowns where the “Edition” field is filtered by the selected “Magazine” via the filter_by parameter. With no magazine selected the Edition dropdown stays empty; once a magazine is chosen, only editions linked to it appear. Reach for this pattern whenever one field’s options should be scoped by another, such as cascaded or conditional menus in publishing systems, location selectors, or product configurations.

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 are standard AutocompleteModelViews; the filter_by parameter is applied automatically by the base view to narrow results for the dependent field - no custom view logic is required.

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.

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