### Install required packages Source: https://django-tomselect.readthedocs.io/en/latest/_sources/example_app/introduction.md.txt Command to install the project's required packages using uv. ```bash uv sync --extra dev ``` -------------------------------- ### TomSelectConfig Example Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt An example of initializing TomSelectConfig with basic parameters for author autocomplete. ```python from django_tomselect.app_settings import TomSelectConfig config = TomSelectConfig( url="author-autocomplete", value_field="id", label_field="name", placeholder="Select an author...", preload="focus", highlight=True, ) ``` -------------------------------- ### Complete Example Configuration Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt A comprehensive example showing configurations for both single-select (author) and multi-select (categories) fields, including plugins. ```python from django import forms from django_tomselect.forms import TomSelectModelChoiceField, TomSelectModelMultipleChoiceField from django_tomselect.app_settings import ( TomSelectConfig, PluginRemoveButton, PluginDropdownFooter ) # Single-select field configuration AUTHOR_CONFIG = TomSelectConfig( url="author-autocomplete", value_field="id", label_field="name", placeholder="Select an author...", highlight=True, open_on_focus=True, preload="focus", plugin_remove_button=PluginRemoveButton(title="Remove", label="×"), ) # Multi-select field configuration CATEGORY_CONFIG = TomSelectConfig( url="category-autocomplete", value_field="id", label_field="name", placeholder="Select categories...", highlight=True, open_on_focus=True, plugin_dropdown_footer=PluginDropdownFooter( title="Categories Footer", footer_class="dropdown-footer" ), max_items=None, # Unlimited selections ) class ArticleForm(forms.Form): author = TomSelectModelChoiceField(config=AUTHOR_CONFIG, label="Author") categories = TomSelectModelMultipleChoiceField(config=CATEGORY_CONFIG, label="Categories") ``` -------------------------------- ### Install development requirements Source: https://django-tomselect.readthedocs.io/en/latest/contributing.html Installs the package with development requirements using uv. ```bash $ uv sync --extra dev ``` -------------------------------- ### Global Settings Example Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt Example of setting global TomSelect configuration in settings.py using TomSelectConfig. ```python # settings.py from django_tomselect.app_settings import TomSelectConfig GLOBAL_TOMSELECT_CONFIG = TomSelectConfig( minimum_query_length=2, highlight=True, preload="focus" ) ``` -------------------------------- ### Install django_tomselect via pip Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt Command to install the django_tomselect package using pip. ```bash pip install django_tomselect ``` -------------------------------- ### ASGI Application Setup Source: https://django-tomselect.readthedocs.io/en/latest/_sources/api/context_processor_and_middleware.md.txt Example of setting up an ASGI application, showing that no additional configuration is needed for the middleware. ```python # No additional configuration needed from django.core.asgi import get_asgi_application application = get_asgi_application() ``` -------------------------------- ### Default Settings Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt Example of how to configure default settings for django-tomselect in settings.py. ```python TOMSELECT = { # Options: "default", "bootstrap4", "bootstrap5" "DEFAULT_CSS_FRAMEWORK": "bootstrap5", # Controls whether to use minified JS/CSS; defaults to opposite of DEBUG "DEFAULT_USE_MINIFIED": True, } ``` -------------------------------- ### Setting up Autocomplete Views Source: https://django-tomselect.readthedocs.io/en/latest/usage.html Example of creating an AutocompleteModelView for Author and configuring its URL. ```python # autocompletes.py from django_tomselect.autocompletes import AutocompleteModelView from .models import Author class AuthorAutocompleteView(AutocompleteModelView): model = Author search_lookups = ["name__icontains", "bio__icontains"] ordering = ["name"] page_size = 20 # Limit how many results to return per request # urls.py from django.urls import path from .autocompletes import AuthorAutocompleteView urlpatterns = [ path("autocomplete/author/", AuthorAutocompleteView.as_view(), name="author-autocomplete"), ] ``` -------------------------------- ### TomSelectConfig with Plugins Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt Example showing how to configure TomSelectConfig with plugins like ClearButton and DropdownHeader. ```python from django_tomselect.app_settings import ( TomSelectConfig, PluginClearButton, PluginDropdownHeader ) config = TomSelectConfig( url="author-autocomplete", value_field="id", label_field="name", highlight=True, plugin_clear_button=PluginClearButton( title="Clear Selection", class_name="clear-button" ), plugin_dropdown_header=PluginDropdownHeader( title="Authors", show_value_field=False, extra_columns={"article_count": "Articles"} ) ) ``` -------------------------------- ### TomSelect initialization with CSP nonce Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt Example of how TomSelect initialization code is rendered with a CSP nonce attribute. ```html ``` -------------------------------- ### CSS Framework Options Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt Examples of how to specify CSS framework options for TomSelectConfig, both directly and globally in settings.py. ```python TomSelectConfig(css_framework="bootstrap5") # Use Bootstrap 5 styles TomSelectConfig(css_framework="bootstrap4") # Use Bootstrap 4 styles TomSelectConfig(css_framework="default") # Use default Tom Select styles ``` ```python # settings.py TOMSELECT = { "DEFAULT_CSS_FRAMEWORK": "bootstrap5" } ``` -------------------------------- ### Configure the Autocomplete View Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt Example of creating a subclass of AutocompleteModelView to provide data to the Tom Select widget. ```python from django_tomselect.autocompletes import AutocompleteModelView from .models import Magazine class MagazineAutocompleteView(AutocompleteModelView): model = Magazine search_lookups = ["name__icontains"] # Fields to search against ordering = ["name"] page_size = 20 ``` -------------------------------- ### Configure Default CSS Framework Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt Example of setting the default CSS framework for django-tomselect in Django's settings.py. ```python TOMSELECT = { "DEFAULT_CSS_FRAMEWORK": "bootstrap5", # Options: "default", "bootstrap4", "bootstrap5" } ``` -------------------------------- ### Install Node dependencies Source: https://django-tomselect.readthedocs.io/en/latest/contributing.html Installs Node.js dependencies required for JavaScript tests. ```bash $ npm install ``` -------------------------------- ### Create example data Source: https://django-tomselect.readthedocs.io/en/latest/_sources/example_app/introduction.md.txt Command to create example data for the project within the virtual environment. ```bash uv run python manage.py create_examples ``` -------------------------------- ### Development Server Startup and Demo Verification Source: https://django-tomselect.readthedocs.io/en/latest/_sources/example_app/rich_author_multi_select.md.txt Commands and steps to verify the end-to-end demo functionality. ```bash uv run python manage.py runserver ``` -------------------------------- ### Run development server Source: https://django-tomselect.readthedocs.io/en/latest/_sources/example_app/introduction.md.txt Command to run the Django development server within the virtual environment. ```bash uv run python manage.py runserver 0.0.0.0:8000 ``` -------------------------------- ### Install django-tomselect via pip Source: https://django-tomselect.readthedocs.io/en/latest/usage.html The command to install the django-tomselect package using pip. ```bash pip install django_tomselect ``` -------------------------------- ### Create superuser Source: https://django-tomselect.readthedocs.io/en/latest/_sources/example_app/introduction.md.txt Command to create a superuser for Django administration within the virtual environment. ```bash uv run python manage.py createsuperuser ``` -------------------------------- ### Clone the repository Source: https://django-tomselect.readthedocs.io/en/latest/_sources/example_app/introduction.md.txt Command to clone the django-tomselect repository. ```bash git clone https://github.com/OmenApps/django-tomselect.git ``` -------------------------------- ### CSP Nonce Example Source: https://django-tomselect.readthedocs.io/en/latest/usage.html Example of how django-tomselect renders inline script tags with a CSP nonce. ```html ``` -------------------------------- ### TomSelectConfig with General Options Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt Example demonstrating TomSelectConfig with various general configuration options for search, display, loading, and creation. ```python config = TomSelectConfig( url="author-autocomplete", value_field="id", label_field="name", placeholder="Search authors...", minimum_query_length=2, open_on_focus=True, preload="focus", highlight=True, load_throttle=300, max_options=50, create=False, create_with_htmx=False, ) ``` -------------------------------- ### Object-level Permissions Example Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt Example of overriding has_object_permission to restrict visibility to objects owned by the current user. ```python class ArticleAutocompleteView(AutocompleteModelView): model = Article def has_object_permission(self, request, obj, action="view"): # Restrict visibility to objects owned by the current user return obj.owner == request.user ``` -------------------------------- ### Install pre-commit Git hook Source: https://django-tomselect.readthedocs.io/en/latest/contributing.html Installs pre-commit as a Git hook for linting and code formatting checks. ```bash $ uv run nox --session=pre-commit -- install ``` -------------------------------- ### Run the Django development server Source: https://django-tomselect.readthedocs.io/en/latest/example_app/introduction.html Command to run the Django development server on all interfaces, port 8000, within the virtual environment. ```bash uv run python manage.py runserver 0.0.0.0:8000 ``` -------------------------------- ### Setting up Autocomplete Views Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt Example of setting up an autocomplete view using AutocompleteModelView for model data, including URL configuration. ```python # autocompletes.py from django_tomselect.autocompletes import AutocompleteModelView from .models import Author class AuthorAutocompleteView(AutocompleteModelView): model = Author search_lookups = ["name__icontains", "bio__icontains"] ordering = ["name"] page_size = 20 # Limit how many results to return per request # urls.py from django.urls import path from .autocompletes import AuthorAutocompleteView urlpatterns = [ path("autocomplete/author/", AuthorAutocompleteView.as_view(), name="author-autocomplete"), ] ``` -------------------------------- ### Form Rendering Examples Source: https://django-tomselect.readthedocs.io/en/latest/usage.html Examples of rendering django-tomselect fields using standard Django template approaches. ```html {{ form.as_p }}
{{ form.magazine }} {% if form.magazine.errors %}
{{ form.magazine.errors }}
{% endif %} {% if form.magazine.help_text %} {{ form.magazine.help_text }} {% endif %}
``` -------------------------------- ### Prepare Results Function Example Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt Example of a prepare_results method in an AutocompleteModelView to add custom data fields for rendering. ```python def prepare_results(self, results): data = [] for author in results: data.append({ "id": author["id"], "name": author["name"], "article_count": author["article_count"], "formatted_name": f"{author['name']} ({author['article_count']} articles)", }) return data ``` -------------------------------- ### Apply migrations Source: https://django-tomselect.readthedocs.io/en/latest/_sources/example_app/introduction.md.txt Command to apply Django database migrations within the project's virtual environment. ```bash uv run python manage.py migrate ``` -------------------------------- ### Get Widget Context Source: https://django-tomselect.readthedocs.io/en/latest/_modules/django_tomselect/widgets.html Gets the context for rendering the widget, handling model instances, global TomSelect setup, and autocomplete views. ```python [docs] def get_context(self, name: str, value: Any, attrs: dict[str, str] | None = None) -> dict[str, Any]: """Get context for rendering the widget.""" self.get_queryset() # Ensure we have model info # Extract configuration value_field = self.value_field or "id" label_field = self.label_field or "name" # Handle possible string representations of model instances value = self._process_string_value(value, value_field, label_field) # Setup global TomSelect if not already done request = get_current_request() if request and not getattr(request, "_tomselect_global_rendered", False): logger.debug("Rendering global TomSelect setup.") self.template_name = "django_tomselect/tomselect_setup.html" request._tomselect_global_rendered = True # Create base context without autocomplete view base_context = self._create_base_context(name, value, attrs, value_field) # Handle selected options without autocomplete view if isinstance(value, dict) and (value.get(value_field) or value.get("id") or value.get("pk")): return self._add_extracted_selected_option(base_context, value, value_field, label_field) # Get autocomplete view and request autocomplete_view = self.get_autocomplete_view() # Return base context if we can't get more info if not autocomplete_view or not request or not self.validate_request(request): logger.warning("Autocomplete view or request not available, returning base context") return base_context # Build full context with autocomplete view context = self._build_full_context(base_context, attrs, autocomplete_view) # Add selected options if value is provided if value and value != "": context["widget"]["selected_options"] = self._get_selected_options(value, autocomplete_view) return context ``` -------------------------------- ### CSS Framework Options Examples Source: https://django-tomselect.readthedocs.io/en/latest/_sources/api/template_tags.md.txt Examples demonstrating the usage of different CSS frameworks with tomselect_media. ```django {# Default styling #} {% tomselect_media %} ``` ```django {# Bootstrap 4 #} {% tomselect_media css_framework="bootstrap4" %} ``` ```django {# Bootstrap 5 #} {% tomselect_media css_framework="bootstrap5" %} ``` -------------------------------- ### Custom Authorization Example Source: https://django-tomselect.readthedocs.io/en/latest/usage.html Example of overriding `has_permission` in `AutocompleteModelView` to restrict access based on user organization membership. ```python class OrganizationRestrictedAutocompleteView(AutocompleteModelView): model = Magazine def has_permission(self, request, action="view"): # Check if user belongs to the required organization return request.user.is_authenticated and request.user.organization_id == 42 ``` -------------------------------- ### Overriding Methods in Autocomplete Views - Example Source: https://django-tomselect.readthedocs.io/en/latest/usage.html Example demonstrating how to use `hook_queryset` and `apply_filters` to annotate and filter a queryset. ```python from django.db.models import F from django_tomselect.autocompletes import AutocompleteModelView from .models import Category class CustomAutocompleteView(AutocompleteModelView): model = Category def hook_queryset(self, queryset): return queryset.annotate(is_special=(F('some_field') > 5)) def apply_filters(self, queryset): # Only return "special" categories return queryset.filter(is_special=True) ``` -------------------------------- ### Example View Implementation Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt A sample implementation of a Django view that integrates searching, filtering, ordering, and result preparation for TomSelect autocompletes. ```python from django.db.models import Count, Q, F from django_tomselect.autocompletes import AutocompleteModelView from .models import Category class CategoryAutocompleteView(AutocompleteModelView): model = Category search_lookups = ["name__icontains", "parent__name__icontains"] ordering = ["name"] page_size = 20 def hook_queryset(self, queryset): # Annotate with counts or other prefetch logic return queryset.annotate(article_count=Count("article")) def apply_filters(self, queryset): # Use built-in filtering logic. If `f='parent__id='` is provided, # this method will apply that filter automatically. return super().apply_filters(queryset) def search(self, queryset, query): # Add custom search conditions in addition to the configured search_lookups if query: q_objects = Q() for lookup in self.search_lookups: q_objects |= Q(**{lookup: query}) # Add custom fields to search: q_objects |= Q(articles__title__icontains=query) return queryset.filter(q_objects).distinct() return queryset def prepare_results(self, results): # Format results for JSON response data = [] for cat in results: data.append({ "id": cat["id"], "name": cat["name"], "article_count": cat["article_count"], }) return data ``` -------------------------------- ### Field-level Override Example Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt Example demonstrating how to override global TomSelect settings for a specific form field using TomSelectModelChoiceField and TomSelectConfig. ```python from django import forms from django_tomselect.forms import TomSelectModelChoiceField from django_tomselect.app_settings import TomSelectConfig class AuthorForm(forms.Form): author = TomSelectModelChoiceField( config=TomSelectConfig( url="author-autocomplete", minimum_query_length=1, # Overrides the global setting of 2 highlight=True ) ) ``` -------------------------------- ### setup Method Source: https://django-tomselect.readthedocs.io/en/latest/_modules/django_tomselect/autocompletes.html Sets up the view with request parameters. ```python @classmethod def setup(cls, request: HttpRequest | Any, *args: Any, **kwargs: Any) -> None: """Set up the view with request parameters.""" ``` -------------------------------- ### Install Playwright browsers and run subset of browser tests Source: https://django-tomselect.readthedocs.io/en/latest/contributing.html Installs Chromium for Playwright and runs a subset of browser tests directly with pytest. ```bash $ PLAYWRIGHT_BROWSERS_PATH=/tmp/playwright-browsers uv run playwright install chromium $ PLAYWRIGHT_BROWSERS_PATH=/tmp/playwright-browsers uv run pytest example_project/test_browser.py ``` -------------------------------- ### Working with ModelForms Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt Example of using TomSelectModelChoiceField and TomSelectModelMultipleChoiceField with Django ModelForms. ```python from django import forms from django_tomselect.forms import TomSelectModelChoiceField, TomSelectModelMultipleChoiceField from django_tomselect import TomSelectConfig from .models import Article class ArticleForm(forms.ModelForm): magazine = TomSelectModelChoiceField( config=TomSelectConfig( url="autocomplete-magazine", value_field="id", label_field="name", ) ) authors = TomSelectModelMultipleChoiceField( config=TomSelectConfig( url="autocomplete-author", value_field="id", label_field="name", placeholder="Select authors...", max_items=None, # Allow any number of authors ) ) class Meta: model = Article fields = ["title", "magazine", "authors"] ``` -------------------------------- ### Example 6 Source: https://django-tomselect.readthedocs.io/en/latest/_modules/django_tomselect/widgets.html This method gets the context for rendering the widget, marking it as multiple selection. ```python context = super().get_context(name, value, attrs) context["widget"]["is_multiple"] = True return context ``` -------------------------------- ### Dropdown Footer "Create New" Link Example Source: https://django-tomselect.readthedocs.io/en/latest/api/config.html Example demonstrating how to enable the "Create New" link in the dropdown footer using `show_create=True` and `PluginDropdownFooter`. ```python from django_tomselect.app_settings import TomSelectConfig, PluginDropdownFooter class ArticleForm(forms.Form): author = TomSelectModelChoiceField( config=TomSelectConfig( url='author-autocomplete', show_create=True, # Enable the create link plugin_dropdown_footer=PluginDropdownFooter( create_view_label="Add New Author", ), ) ) ``` ```python from django_tomselect.autocompletes import AutocompleteModelView class AuthorAutocompleteView(AutocompleteModelView): model = Author search_lookups = ['name__icontains'] create_url = 'author-create' # URL name for the create view ``` -------------------------------- ### CSS Framework Options Source: https://django-tomselect.readthedocs.io/en/latest/usage.html Examples of setting the CSS framework for TomSelectConfig. ```python TomSelectConfig(css_framework="bootstrap5") # Use Bootstrap 5 styles ``` ```python TomSelectConfig(css_framework="bootstrap4") # Use Bootstrap 4 styles ``` ```python TomSelectConfig(css_framework="default") # Use default Tom Select styles ``` -------------------------------- ### Edition Year List Source: https://django-tomselect.readthedocs.io/en/latest/_sources/example_app/introduction.md.txt A list of years for the Edition model, used to demonstrate the AutocompleteIterablesView. ```python # A list of years for the Edition model # Used to demonstrate the AutocompleteIterablesView edition_year = [ 2020, 2021, 2022, 2023, 2024, 2025, ] ``` -------------------------------- ### Basic Form Integration Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt Example of integrating TomSelectModelChoiceField into a regular Django form. ```python from django import forms from django_tomselect.forms import TomSelectModelChoiceField from django_tomselect import TomSelectConfig class MagazineFilterForm(forms.Form): magazine = TomSelectModelChoiceField( config=TomSelectConfig( url="autocomplete-magazine", value_field="id", label_field="name", placeholder="Select a magazine...", preload="focus", highlight=True, ) ) ``` -------------------------------- ### Complete Configuration Example Source: https://django-tomselect.readthedocs.io/en/latest/api/config.html A comprehensive example showcasing various configuration options available in TomSelectConfig, including core settings, filtering, display, behavior, performance, feature toggles, and framework settings. ```python from django_tomselect.app_settings import TomSelectConfig, Const config = TomSelectConfig( # Core Settings url='book-autocomplete', value_field='id', label_field='name', create_field='', # Filtering - supports multiple formats (see "Dependent Fields" section below) filter_by=('category', 'category_id'), # Simple: filter by category form field # Or for multiple filters: # filter_by=[ # ('category', 'category_id'), # Const('published', 'status'), # Always filter to published status # ], exclude_by=(), # No excludes (default) use_htmx=False, # Enable HTMX integration attrs={}, # Display Settings placeholder='Select a value', minimum_query_length=2, max_items=None, max_options=None, # Behavior Settings preload='focus', # Can be 'focus', True, or False highlight=True, open_on_focus=True, close_after_select=None, hide_selected=True, hide_placeholder=None, create=False, # Enable item creation create_filter=None, # Filter for new items create_with_htmx=False, # Use HTMX for item creation # Performance Settings load_throttle=300, loading_class='loading', # Feature Toggles (all default to False) show_list=False, show_create=False, show_detail=False, show_update=False, show_delete=False, # Framework Settings css_framework='bootstrap5', use_minified=True, # Plugins plugin_checkbox_options=PluginCheckboxOptions(), plugin_clear_button=PluginClearButton(), plugin_dropdown_header=PluginDropdownHeader(), plugin_dropdown_footer=PluginDropdownFooter(), plugin_dropdown_input=PluginDropdownInput(), plugin_remove_button=PluginRemoveButton() ) ``` -------------------------------- ### Dependent/Chained Fields Example Source: https://django-tomselect.readthedocs.io/en/latest/_sources/usage.md.txt An example of how to configure dependent fields in Django forms using TomSelectModelChoiceField, where one field's options are filtered based on another's selection. ```python from django import forms from django_tomselect.forms import TomSelectModelChoiceField from django_tomselect import TomSelectConfig class CategoryForm(forms.Form): category = TomSelectModelChoiceField( config=TomSelectConfig( url="category-autocomplete", value_field="id", label_field="name", ), ) subcategory = TomSelectModelChoiceField( config=TomSelectConfig( url="subcategory-autocomplete", value_field="id", label_field="name", # Instructs the subcategory field to dynamically filter by the selected category filter_by=("category", "category_id"), ), ) ``` -------------------------------- ### Runtime Logging Control Source: https://django-tomselect.readthedocs.io/en/latest/_sources/api/utilities.md.txt Example of getting a module-specific logger and controlling its enabled state at runtime. ```python from django_tomselect.logging import get_logger # Get a module-specific logger logger = get_logger("django_tomselect.autocompletes") # Check if logging is enabled if logger.enabled: print("Logging is active") # Disable logging for this logger logger.enabled = False ```