Exclude-By Primary Author

Example Overview

This example shows how to dynamically exclude options in one field based on the selection in another, using the exclude_by parameter. The “Contributing Authors” field excludes whoever is chosen as “Primary Author” so the same person can’t fill both roles, and stays empty until a Primary Author is selected. Reach for this pattern whenever overlapping selections between two related fields would be invalid or redundant.

Visual Examples

Screenshot: Exclude-By Primary Author

Key Code Segments

Forms

The form uses TomSelectModelChoiceField for the “Primary Author” and TomSelectModelMultipleChoiceField for “Contributing Authors”. The exclude_by parameter ensures contributing authors exclude the selected primary author.

Explanation:

  • The exclude_by parameter in the contributing_authors field ensures that any selected “Primary Author” is removed from the available options in the “Contributing Authors” field.

  • The RemoveButton plugin improves user interaction by enabling quick removal of selected contributing authors.

Templates

The form is rendered in the exclude_by.html template, highlighting the exclusion mechanism between the two fields.

Key Elements:

  • Bootstrap 5 for clean and modern styling.

  • The exclusion logic is visually reflected in the dropdowns as selections are made.

Autocomplete Views

The autocomplete-author endpoint serves data for both fields, ensuring proper exclusion logic based on the exclude_by parameter.

  • We override the get_queryset method to filter authors based on the selected magazine (if any).

  • The hook_prepare_results method adds a formatted name to each author result for better readability.

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