Tagging Publications

Example Overview

  • Objective: This example demonstrates how to implement tagging functionality in a Django form using django_tomselect. Users can create new tags dynamically or select from existing ones. The tags are validated and saved to the database with support for autocomplete and real-time updates.

    • Features Highlighted:

      • Support for dynamic tag creation with the create feature.

      • Real-time autocomplete of existing tags using django_tomselect.

  • Use Case:

    • Content management systems where articles or products require tagging for organization and filtering.

    • Applications requiring user-generated metadata to categorize or describe entities.

Visual Examples

Screenshot: Tagging Screenshot: Tagging (invalid tag cleaning)

Key Code Segments

Forms

The form uses a custom DynamicTagField, a subclass of TomSelectMultipleChoiceField, to allow dynamic creation and selection of tags.

The most complex part of the form is the clean_tags method, which validates and saves tags to the database.

Explanation:

  • The DynamicTagField allows users to add new tags on the fly.

  • The clean_tags method ensures all tags are validated and saved to the database.

Templates

The form is rendered in the tagging_publication.html template, providing an intuitive interface for managing tags.

Upon form submission, the clean_tags method is called to validate and save the tags to the database. If successful, the user is redirected to a success page; otherwise, the form is re-rendered with error messages.

Autocomplete Views

The autocomplete-publication-tag endpoint provides tag suggestions based on user input.

In this example, we are mixing iterable-based choices with a model-based autocomplete field, so we need to override the get_iterable method to provide the iterable interface for the TomSelectIterablesWidget.

Views

The tagging view processes the form data and displays a success message with the selected tags.

Design and Implementation Notes

  • Key Features:

    • create feature allows users to add new tags dynamically.

    • Form validation ensures only valid tags are added, preventing duplicates or invalid formats.

  • Design Decisions:

    • The DynamicTagField simplifies the addition of new tags while reusing existing logic.

    • Error messages and validation rules provide clear feedback to users.