Exclude-By Primary Author

Example Overview

  • Objective: This example showcases how to dynamically exclude certain options in one field based on the selection in another field using django_tomselect. Specifically, the “Contributing Authors” field excludes the “Primary Author” selection to prevent redundant choices. Also, if no Primary Author is selected, the Contributing Authors field will remain empty.

    • Problem Solved: Maintaining data integrity and logical consistency.

  • Use Case:

    • Assigning roles to users where overlapping responsibilities are invalid (e.g., primary and secondary roles in a project).

    • Preventing duplicate selections in multi-step forms or hierarchical data inputs.

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.

Design and Implementation Notes

  • Key Features:

    • Dynamic exclusion using exclude_by.

  • Design Decisions:

    • Chose TomSelectModelMultipleChoiceField for contributing authors to allow multi-selection.

    • The exclude_by parameter ensures clean and efficient backend filtering without additional custom JavaScript.

  • Potential Extensions:

    • Add metadata to the dropdown options, such as the number of articles authored.

    • Extend the exclusion logic to handle multiple fields (e.g., exclude all team leads from a team member selection).

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