Tagging Publications

Example Overview

This example implements tagging in a Django form with django_tomselect. Users can autocomplete existing tags or create new ones on the fly with the create feature, and the tags are validated and saved to the database on submit. Reach for this pattern in content management systems or anywhere users generate metadata to categorize 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 shown 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 the form field (DynamicTagField, built on TomSelectMultipleChoiceField) drives the iterables widget, while PublicationTagAutocompleteView is a model-based view. To bridge the two, we override get_iterable so the model view also emits the {value, label} iterable shape the TomSelectIterablesWidget expects.

Views

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