### Install django-select2 Package Source: https://django-select2.readthedocs.io/en/latest/_sources/index Command to install the django-select2 package using pip. This is the first step for setting up the library in a Django project. ```shell python3 -m pip install django-select2 ``` -------------------------------- ### Install Redis for Caching Source: https://django-select2.readthedocs.io/en/latest/index Installs Redis server and the django-redis Python client, necessary for persistent cache backends in multi-server setups. ```shell # Debian sudo apt-get install redis-server # macOS brew install redis # install Redis python client python3 -m pip install django-redis ``` -------------------------------- ### Install Django-Select2 Source: https://django-select2.readthedocs.io/en/latest/index Installs the django-select2 package using pip. Ensure you are using python3. ```shell python3 -m pip install django-select2 ``` -------------------------------- ### Install Redis Server Source: https://django-select2.readthedocs.io/en/latest/_sources/index Commands for installing Redis server on Debian and macOS. Redis is recommended as a persistent cache backend for django-select2 in multi-server environments. ```shell # Debian sudo apt-get install redis-server # macOS brew install redis ``` -------------------------------- ### Install Redis Python Client Source: https://django-select2.readthedocs.io/en/latest/_sources/index Command to install the django-redis Python client library using pip. This is required to use Redis as a cache backend for django-select2. ```shell python3 -m pip install django-redis ``` -------------------------------- ### Django-Select2: ModelSelect2Widget Example Usage Source: https://django-select2.readthedocs.io/en/latest/django_select2 Provides example implementations of ModelSelect2Widget within Django models and forms. It demonstrates how to configure search fields and integrate the widget into 'Meta' classes or directly in form field definitions. ```python class MyWidget(ModelSelect2Widget): search_fields = [ 'title__icontains', ] class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ('my_field', ) widgets = { 'my_field': MyWidget, } # Or: class MyForm(forms.Form): my_choice = forms.ChoiceField( widget=ModelSelect2Widget( model=MyOtherModel, search_fields=['title__icontains'] ) ) ``` -------------------------------- ### JavaScript Initialization of Django-Select2 Source: https://django-select2.readthedocs.io/en/latest/django_select2 Guides on how to initialize Select2 fields using the provided JavaScript plugin, both automatically and manually. ```APIDOC ## JavaScript Initialization ### Description DjangoSelect2 automatically initializes Select2 fields when `{{ form.media }}` is included in your template. For dynamic forms or manual control, use the `djangoSelect2()` jQuery plugin. ### Method N/A (JavaScript usage) ### Endpoint N/A (JavaScript usage) ### Parameters N/A (JavaScript usage) ### Request Example ```javascript // Automatic initialization (include form.media in template) // Manual initialization $('.django-select2').djangoSelect2(); // With options $('.django-select2').djangoSelect2({ minimumInputLength: 0, placeholder: 'Select an option', }); ``` ### Response N/A (JavaScript usage) ``` -------------------------------- ### Configure Django-Select2 Options via JavaScript Source: https://django-select2.readthedocs.io/en/latest/django_select2 Demonstrates how to pass Select2 configuration options directly through JavaScript when initializing the widget. This example sets the minimum input length to 0 and defines a placeholder text for the select field. ```javascript $('.django-select2').djangoSelect2({ minimumInputLength: 0, placeholder: 'Select an option', }); ``` -------------------------------- ### Create Django Class-Based View for Book Creation Source: https://django-select2.readthedocs.io/en/latest/_sources/index Example Django CreateView to render the BookForm. This view uses the model and form defined previously to handle book creation requests. ```python # views.py from django.views import generic from . import forms, models class BookCreateView(generic.CreateView): model = models.Book form_class = forms.BookForm success_url = "/" ``` -------------------------------- ### Define Django Model for Book Source: https://django-select2.readthedocs.io/en/latest/_sources/index Example Django model definition for a 'Book' with ForeignKey and ManyToManyField relationships to the user model. Used to demonstrate django-select2 widgets. ```python # models.py from django.conf import settings from django.db import models class Book(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) co_authors = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='co_authored_by') ``` -------------------------------- ### Create Django Forms with Select2 Widgets Source: https://django-select2.readthedocs.io/en/latest/_sources/index Example Django form definitions using custom ModelSelect2Widget and ModelSelect2MultipleWidget from django_select2. These widgets enhance ForeignKey and ManyToManyField selections. ```python # forms.py from django import forms from django_select2 import forms as s2forms from . import models class AuthorWidget(s2forms.ModelSelect2Widget): search_fields = [ "username__icontains", "email__icontains", ] class CoAuthorsWidget(s2forms.ModelSelect2MultipleWidget): search_fields = [ "username__icontains", "email__icontains", ] class BookForm(forms.ModelForm): class Meta: model = models.Book fields = "__all__" widgets = { "author": AuthorWidget, "co_authors": CoAuthorsWidget, } ``` -------------------------------- ### AutoResponseView: Handle GET requests for Django-Select2 widgets Source: https://django-select2.readthedocs.io/en/latest/_modules/django_select2/views The AutoResponseView handles GET requests for Django-Select2 model widgets. It retrieves widget configurations, filters the queryset based on search terms and dependent fields, and returns results as a JSON response. The response includes 'results' (formatted instances) and 'more' (pagination indicator). ```python """JSONResponse views for model widgets.""" from django.core import signing from django.core.signing import BadSignature from django.http import Http404, JsonResponse from django.utils.module_loading import import_string from django.views.generic.list import BaseListView from .cache import cache from .conf import settings class AutoResponseView(BaseListView): """ View that handles requests from heavy model widgets. The view only supports HTTP's GET method. """ def get(self, request, *args, **kwargs): """ Return a :class:`.django.http.JsonResponse`. Each result will be rendered by the widget's :func:`django_select2.forms.ModelSelect2Mixin.result_from_instance` method. Example:: { 'results': [ { 'text': "foo", 'id': 123 } ], 'more': true } """ self.widget = self.get_widget_or_404() self.term = kwargs.get("term", request.GET.get("term", "")) self.object_list = self.get_queryset() context = self.get_context_data() return JsonResponse( { "results": [ self.widget.result_from_instance(obj, request) for obj in context["object_list"] ], "more": context["page_obj"].has_next(), }, encoder=import_string(settings.SELECT2_JSON_ENCODER), ) def get_queryset(self): """Get QuerySet from cached widget.""" kwargs = { model_field_name: self.request.GET.get(form_field_name) for form_field_name, model_field_name in self.widget.dependent_fields.items() } kwargs.update( { f"{model_field_name}__in": self.request.GET.getlist( f"{form_field_name}[]", [] ) for form_field_name, model_field_name in self.widget.dependent_fields.items() } ) return self.widget.filter_queryset( self.request, self.term, self.queryset, **{k: v for k, v in kwargs.items() if v}, ) def get_paginate_by(self, queryset): """Paginate response by size of widget's `max_results` parameter.""" return self.widget.max_results def get_widget_or_404(self): """ Get and return widget from cache. Raises: Http404: If if the widget can not be found or no id is provided. Returns: ModelSelect2Mixin: Widget from cache. """ field_id = self.kwargs.get("field_id", self.request.GET.get("field_id", None)) if not field_id: raise Http404('No "field_id" provided.') try: key = signing.loads(field_id) except BadSignature: raise Http404('Invalid "field_id".') else: cache_key = f"{settings.SELECT2_CACHE_PREFIX}{key}" widget_dict = cache.get(cache_key) if widget_dict is None: raise Http404("field_id not found") if widget_dict.pop("url") != self.request.path: raise Http404("field_id was issued for the view.") qs, qs.query = widget_dict.pop("queryset") self.queryset = qs.all() widget_dict["queryset"] = self.queryset widget_cls = widget_dict.pop("cls") return widget_cls(**widget_dict) ``` -------------------------------- ### Configure Django-Select2 Options via Django Widget Attributes Source: https://django-select2.readthedocs.io/en/latest/django_select2 Provides an example of configuring Select2 widget options using `data-*` attributes within the Django form definition. These attributes are passed to the widget's `attrs` dictionary and are automatically picked up by Select2 for initialization, such as setting minimum input length and placeholder. ```python class MyForm(forms.Form): my_field = forms.ModelMultipleChoiceField( widget=ModelSelect2MultipleWidget( model=MyModel search_fields=['another_field'] attrs={ "data-minimum-input-length": 0, "data-placeholder": "Select an option", "data-close-on-select": "false", } ) ) ``` -------------------------------- ### Configure Django-Select2 Cache Backend Source: https://django-select2.readthedocs.io/en/latest/django_select2 Sets the cache backend for Django-Select2 to ensure consistent state across multiple machines. Requires a cache backend like Redis or Memcached configured in settings.py. The example shows how to set up a default cache and a specific 'select2' cache using django-redis. ```python CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, 'select2': { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/2", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } # Set the cache backend to select2 SELECT2_CACHE_BACKEND = 'select2' ``` -------------------------------- ### Django-Select2: ModelSelect2Mixin Search Fields Example Source: https://django-select2.readthedocs.io/en/latest/django_select2 Shows how to define 'search_fields' within the ModelSelect2Mixin for filtering QuerySets. This is crucial for implementing searchable dropdowns based on model attributes. ```python class ModelSelect2Mixin(object): # ... other methods ... search_fields = [] # Example: # search_fields = [ # 'title__icontains', # ] ``` -------------------------------- ### Custom ModelSelect2TagWidget Implementation in Django Source: https://django-select2.readthedocs.io/en/latest/django_select2 Example of extending `ModelSelect2TagWidget` to implement `value_from_datadict`. This custom method handles the creation of new objects based on user input when tags are added and ensures primary keys are correctly returned. It requires defining the `queryset` and assumes the `MyModel` has a 'title' field for object creation. ```python class MyModelSelect2TagWidget(ModelSelect2TagWidget): queryset = MyModel.objects.all() def value_from_datadict(self, data, files, name): '''Create objects for given non-pimary-key values. Return list of all primary keys.''' values = set(super().value_from_datadict(data, files, name)) # This may only work for MyModel, if MyModel has title field. # You need to implement this method yourself, to ensure proper object creation. pks = self.queryset.filter(**{'pk__in': list(values)}).values_list('pk', flat=True) pks = set(map(str, pks)) cleaned_values = list(pks) for val in values - pks: cleaned_values.append(self.queryset.create(title=val).pk) return cleaned_values ``` -------------------------------- ### Customize Django-Select2 JavaScript Files Source: https://django-select2.readthedocs.io/en/latest/_modules/django_select2/conf This code example illustrates how to customize the JavaScript files used by Django-Select2. You can specify a different path to the Select2 JS file or disable loading any JS by providing an empty list. This is useful for serving Select2 from local static resources or using a specific version. ```python # Use a custom path for the Select2 JS file SELECT2_JS = ['assets/js/select2.min.js'] # Disable loading any Select2 JS files SELECT2_JS = [] ``` -------------------------------- ### Select2 Tag Widget with Dynamic Option Creation Source: https://django-select2.readthedocs.io/en/latest/_modules/django_select2/forms The `Select2TagWidget` class combines `Select2TagMixin`, `Select2Mixin`, and `forms.SelectMultiple` to create a widget that supports Select2's tagging functionality. It allows users to dynamically create new options by typing in the input field. The example demonstrates custom `value_from_datadict` and `optgroups` methods for handling comma-separated values, suitable for Django's `ArrayField`. ```python class Select2TagWidget(Select2TagMixin, Select2Mixin, forms.SelectMultiple): """ Select2 drop in widget with tagging support. It allows to dynamically create new options from text input by the user. Example for :class:`.django.contrib.postgres.fields.ArrayField`:: class MyWidget(Select2TagWidget): def value_from_datadict(self, data, files, name): values = super().value_from_datadict(data, files, name) return ",".join(values) def optgroups(self, name, value, attrs=None): values = value[0].split(',') if value[0] else [] selected = set(values) subgroup = [self.create_option(name, v, v, selected, i) for i, v in enumerate(values)] return [(None, subgroup, 0)] """ ``` -------------------------------- ### Add Book Create View to URLs Source: https://django-select2.readthedocs.io/en/latest/index Maps the BookCreateView to the '/book/create' URL path in the Django project's urls.py. ```python # urls.py from django.urls import include, path from . import views urlpatterns = [ # … other patterns path("select2/", include("django_select2.urls")), # … other patterns path("book/create", views.BookCreateView.as_view(), name="book-create"), ] ``` -------------------------------- ### Customizing Instance Label in Django Select2 Widget Source: https://django-select2.readthedocs.io/en/latest/_modules/django_select2/forms This Python method, `label_from_instance`, is part of a Django Select2 widget. It allows developers to customize how each model instance is represented as a label in the select options. By overriding this method, you can format the display text, for example, by converting it to uppercase as shown in the example. ```python def label_from_instance(self, obj): """ Return option label representation from instance. Can be overridden to change the representation of each choice. Example usage:: class MyWidget(ModelSelect2Widget): def label_from_instance(obj): return str(obj.title).upper() Args: obj (django.db.models.Model): Instance of Django Model. Returns: str: Option label. """ return str(obj) ``` -------------------------------- ### GET /api/field-data (AutoResponseView) Source: https://django-select2.readthedocs.io/en/latest/_modules/django_select2/views Handles HTTP GET requests from django-select2 heavy model widgets. Returns a JSON response containing paginated results from a filtered queryset, with each result rendered using the widget's result_from_instance method. Supports dependent fields filtering and custom pagination. ```APIDOC ## GET /api/field-data ### Description Returns paginated JSON results for Select2 heavy model widgets. Each result is rendered by the widget's ModelSelect2Mixin.result_from_instance method. Supports filtering via dependent fields and search terms. ### Method GET ### Endpoint /api/field-data ### Parameters #### Query Parameters - **field_id** (string) - Required - Signed widget identifier used to retrieve widget configuration from cache - **term** (string) - Optional - Search term for filtering queryset results - **page** (integer) - Optional - Page number for pagination (default: 1) - **{form_field_name}** (string) - Optional - Dependent field filter values - **{form_field_name}[]** (array) - Optional - Multiple dependent field filter values ### Request Example ``` GET /api/field-data?field_id=abc123def456&term=foo&page=1 ``` ### Response #### Success Response (200 OK) - **results** (array) - List of paginated result objects - **id** (mixed) - Unique identifier for the result item - **text** (string) - Display text for the result item - **more** (boolean) - Indicates if additional pages of results are available #### Response Example ```json { "results": [ { "id": 123, "text": "foo" }, { "id": 124, "text": "foobar" } ], "more": true } ``` #### Error Response (404 Not Found) - Returned when field_id is missing, invalid, or not found in cache - Returned when field_id was issued for a different view URL ### Implementation Details - **View Class**: AutoResponseView (extends BaseListView) - **Supported Methods**: GET only - **Response Format**: JSON (via JsonResponse with configurable encoder from SELECT2_JSON_ENCODER setting) - **Pagination**: Automatically paginated by widget's max_results parameter - **Widget Caching**: Widget configuration retrieved from cache using signed field_id - **Dependent Fields**: Supports filtering by dependent form field values ``` -------------------------------- ### Add Book Creation View to Django URLs Source: https://django-select2.readthedocs.io/en/latest/_sources/index Configuration snippet for Django's URL configuration (urls.py) to map a URL path to the BookCreateView. Includes the django_select2 URLs as well. ```python # urls.py from django.urls import include, path from . import views urlpatterns = [ # … other patterns path("select2/", include("django_select2.urls")), # … other patterns path("book/create", views.BookCreateView.as_view(), name="book-create"), ] ``` -------------------------------- ### URLs Module Source: https://django-select2.readthedocs.io/en/latest/_sources/django_select2 The django_select2.urls module handles URL configuration and routing for Select2 API endpoints. Provides URL patterns for data retrieval and widget initialization. ```APIDOC ## URLs Module ### Module django_select2.urls ### Description Handles URL configuration and routing for Django Select2 API endpoints. Includes URL patterns for accessing Select2 data and widget functionality. ### Usage ```python from django.urls import path, include urlpatterns = [ path('select2/', include('django_select2.urls')), ] ``` ``` -------------------------------- ### Add django_select2 to INSTALLED_APPS Source: https://django-select2.readthedocs.io/en/latest/_sources/index Configuration snippet for Django's settings.py to include 'django_select2' in INSTALLED_APPS. Ensures Django's admin app is also enabled for compatibility. ```python INSTALLED_APPS = [ # other django apps… 'django.contrib.admin', # other 3rd party apps… 'django_select2', ] ``` -------------------------------- ### URL Configuration for Django-Select2 Source: https://django-select2.readthedocs.io/en/latest/django_select2 Instructions on how to include Django-Select2's URL patterns in your project's main URL configuration. ```APIDOC ## Include Django-Select2 URLs ### Description Add the Django-Select2 URL configuration to your project's `urls.py` file to enable its views, particularly for model widgets. ### Method N/A (This is a URL configuration instruction) ### Endpoint N/A (This is a URL configuration instruction) ### Parameters N/A (This is a URL configuration instruction) ### Request Example ```python # urls.py from django.urls import path, include urlpatterns = [ # ... other url patterns path('select2/', include('django_select2.urls')), ] ``` ### Response N/A (This is a URL configuration instruction) ``` -------------------------------- ### Django Template for Book Creation Form Source: https://django-select2.readthedocs.io/en/latest/_sources/index Basic HTML template for rendering the BookForm. Includes form media for CSS and JS, and uses {{ form.as_p }} to display form fields. ```html Create Book {{ form.media.css }}

Create a new Book

{% csrf_token %} {{ form.as_p }} ``` -------------------------------- ### Django-Select2: ModelSelect2Mixin Get Queryset Method Source: https://django-select2.readthedocs.io/en/latest/django_select2 Presents the 'get_queryset' method of ModelSelect2Mixin, responsible for returning the QuerySet used for populating choices. It can be based on a predefined 'queryset' attribute or a 'model' attribute. ```python def get_queryset(self): """Return QuerySet based on `queryset` or `model`.""" # Returns: QuerySet of available choices. ``` -------------------------------- ### Get empty_label property from ModelChoiceIterator Source: https://django-select2.readthedocs.io/en/latest/_modules/django_select2/forms Returns the empty_label from the associated ModelChoiceIterator field if available, otherwise returns an empty string. This property is used by Select2 widgets to display placeholder text for unselected options. ```python @property def empty_label(self): if isinstance(self.choices, ModelChoiceIterator): return self.choices.field.empty_label return "" ``` -------------------------------- ### Include Django-Select2 URLs Source: https://django-select2.readthedocs.io/en/latest/index Includes the django_select2 URL patterns in your project's root URL configuration. ```python from django.urls import include, path urlpatterns = [ # other patterns… path("select2/", include("django_select2.urls")), # other patterns… ] ``` -------------------------------- ### Configure Django INSTALLED_APPS Source: https://django-select2.readthedocs.io/en/latest/index Adds 'django_select2' to your project's INSTALLED_APPS setting. It's also required to have 'django.contrib.admin' enabled since version 8. ```python INSTALLED_APPS = [ # other django apps… 'django.contrib.admin', # other 3rd party apps… 'django_select2', ] ``` -------------------------------- ### Get list of search field lookup names Source: https://django-select2.readthedocs.io/en/latest/_modules/django_select2/forms Returns the list of search_fields that define ORM lookups for filtering the QuerySet. Raises NotImplementedError if search_fields is not defined, ensuring search functionality is properly configured. ```python def get_search_fields(self): """Return list of lookup names.""" if self.search_fields: return self.search_fields raise NotImplementedError( ``` -------------------------------- ### Create Django View for Book Form Source: https://django-select2.readthedocs.io/en/latest/index Implements a generic CreateView in Django to render the BookForm. It specifies the model, form class, and success URL. ```python # views.py from django.views import generic from . import forms, models class BookCreateView(generic.CreateView): model = models.Book form_class = forms.BookForm success_url = "/" ``` -------------------------------- ### Django-Select2 Widget - Select2Widget Source: https://django-select2.readthedocs.io/en/latest/django_select2 A drop-in Select2 widget for single select fields. It integrates seamlessly with Django forms, providing enhanced user experience for choice selections. Example usage with ModelForm and Form shown. ```python from django import forms class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ('my_field', ) widgets = { 'my_field': Select2Widget } class MyForm(forms.Form): my_choice = forms.ChoiceField(widget=Select2Widget) @property def media(self): # Construct Media as a dynamic property. # Note: For more information visit https://docs.djangoproject.com/en/stable/topics/forms/media/#media-as-a-dynamic-property pass ``` -------------------------------- ### Initialize ModelSelect2Mixin with model, queryset, and search configuration Source: https://django-select2.readthedocs.io/en/latest/_modules/django_select2/forms Constructor that overrides class parameters with keyword arguments. Accepts model, queryset, search_fields, and max_results to configure the widget for Select2 auto-complete functionality. Sets default data_view to 'django_select2:auto-json' for AJAX requests. ```python def __init__(self, *args, **kwargs): """ Overwrite class parameters if passed as keyword arguments. Args: model (django.db.models.Model): Model to select choices from. queryset (django.db.models.query.QuerySet): QuerySet to select choices from. search_fields (list): List of model lookup strings. max_results (int): Max. JsonResponse view page size. """ self.model = kwargs.pop("model", self.model) self.queryset = kwargs.pop("queryset", self.queryset) self.search_fields = kwargs.pop("search_fields", self.search_fields) self.max_results = kwargs.pop("max_results", self.max_results) defaults = {"data_view": "django_select2:auto-json"} defaults.update(kwargs) super().__init__(*args, **defaults) ``` -------------------------------- ### AutoResponseView Methods Reference Source: https://django-select2.readthedocs.io/en/latest/_modules/django_select2/views Detailed reference for internal methods of the AutoResponseView class. These methods handle widget retrieval, queryset filtering, pagination, and response formatting for django-select2 heavy model widgets. ```APIDOC ## AutoResponseView Internal Methods ### get_widget_or_404() #### Description Retrieves the Select2 widget configuration from cache using the signed field_id parameter. Validates the field_id and ensures it matches the current request URL. #### Returns - **ModelSelect2Mixin** - Widget instance from cache #### Raises - **Http404** - If field_id is not provided - **Http404** - If field_id signature is invalid (BadSignature) - **Http404** - If field_id is not found in cache - **Http404** - If field_id was issued for a different view URL #### Logic Flow 1. Extract field_id from kwargs or GET parameters 2. Decode field_id using signing.loads() 3. Construct cache key using SELECT2_CACHE_PREFIX setting 4. Retrieve widget_dict from cache 5. Validate widget URL matches current request path 6. Reconstruct and return widget instance --- ### get_queryset() #### Description Filters and returns the queryset from the cached widget. Applies dependent field filters and search term filtering. #### Returns - **QuerySet** - Filtered queryset from the widget #### Parameters Used - **self.widget** - Cached widget instance - **self.request** - HTTP request object - **self.term** - Search term from request - **self.queryset** - Base queryset from widget cache - **Dependent Fields** - Filter values from GET parameters #### Logic Flow 1. Extract dependent field values from GET parameters 2. Build kwargs for single-value dependent fields 3. Build kwargs for multi-value dependent fields (using __in lookup) 4. Call widget.filter_queryset() with all parameters 5. Return filtered queryset --- ### get_paginate_by(queryset) #### Description Determines pagination size for the queryset response. #### Parameters - **queryset** (QuerySet) - The queryset to paginate #### Returns - **integer** - Number of results per page (from widget.max_results) --- ### get(request, *args, **kwargs) #### Description Main entry point for GET requests. Orchestrates widget retrieval, queryset filtering, and JSON response generation. #### Returns - **JsonResponse** - JSON response with results and more flag #### Process 1. Retrieve widget using get_widget_or_404() 2. Extract search term from kwargs or GET parameters 3. Get filtered queryset via get_queryset() 4. Retrieve paginated context via get_context_data() 5. Transform results using widget.result_from_instance() 6. Return JsonResponse with results array and more flag ``` -------------------------------- ### ModelSelect2Widget for Single Select in Django Source: https://django-select2.readthedocs.io/en/latest/_modules/django_select2/forms The `ModelSelect2Widget` is a Django form widget that integrates with Select2 for a user-friendly single-selection dropdown powered by model choices. It requires specifying the model and fields for searching. The example shows its use within a `ModelForm` and a standalone `forms.Form`. ```python class ModelSelect2Widget(ModelSelect2Mixin, HeavySelect2Widget): """ Select2 drop in model select widget. Example usage:: class MyWidget(ModelSelect2Widget): search_fields = [ 'title__icontains', ] class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ('my_field', ) widgets = { 'my_field': MyWidget, } or:: class MyForm(forms.Form): my_choice = forms.ChoiceField( widget=ModelSelect2Widget( model=MyOtherModel, search_fields=['title__icontains'] ) ) .. tip:: The ModelSelect2(Multiple)Widget will try to get the QuerySet from the fields choices. Therefore you don't need to define a QuerySet, if you just drop in the widget for a ForeignKey field. """ ``` -------------------------------- ### Django-Select2 Configuration Settings Source: https://django-select2.readthedocs.io/en/latest/django_select2 This section details the various settings available to configure Django-Select2's behavior, caching, static file handling, and internationalization. ```APIDOC ## Django-Select2 Configuration ### Description Configuration settings for the Django-Select2 library. ### Method N/A (Configuration) ### Endpoint N/A (Configuration) ### Parameters #### Configuration Settings - **CACHE_BACKEND** (string) - Default: 'default' - Specifies the Django cache backend to use for ensuring consistent state across multiple machines. It's recommended to use an external cache like Memcached or Redis. - **CACHE_PREFIX** (string) - Default: 'select2_' - A prefix for the cache to isolate Django-Select2's cache entries, useful if the cache backend doesn't support multiple databases. - **JS** (list of strings) - Default: ['admin/js/vendor/select2/select2.full.min.js'] - A list of URIs for the Select2 JavaScript files. Can be customized to point to local assets or different versions. - **CSS** (list of strings) - Default: ['admin/css/vendor/select2/select2.min.css'] - A list of URIs for the Select2 CSS files. Allows customization for local assets, additional themes, or to disable default CSS. - **THEME** (string) - Default: 'default' - Specifies the theme to be used for styling Select2 widgets. Custom themes can be applied here. - **I18N_PATH** (string) - Default: 'admin/js/vendor/select2/i18n' - The base URI for Select2 internationalization (i18n) files. Can be set to local assets for offline use. - **I18N_AVAILABLE_LANGUAGES** (list of strings) - Default: [...] - A list of ISO 639-1 language codes supported by Select2. Django-Select2 uses this to load appropriate translations. - **JSON_ENCODER** (string) - Default: 'django.core.serializers.json.DjangoJSONEncoder' - The JSON encoder used for generating API responses for model widgets. Can be overridden for custom serialization needs, especially for non-standard primary keys. ### Request Example No direct request examples as these are settings applied in `settings.py`. Example `settings.py` configuration: ```python SELECT2_CACHE_BACKEND = 'select2' SELECT2_JS = ['assets/js/select2.min.js'] SELECT2_CSS = [ 'assets/css/select2.css', 'assets/css/select2-theme.css', ] ``` ### Response N/A (Configuration) ### Response Example N/A (Configuration) ``` -------------------------------- ### Configuring Select2 Options Source: https://django-select2.readthedocs.io/en/latest/django_select2 Explains how to configure Select2 options either through JavaScript or by using `data-` attributes on Django widget instances. ```APIDOC ## Configuring Select2 Options ### Description Select2 widget options can be configured using either JavaScript directly or via `data-` attributes passed through the widget's `attrs` dictionary in Django forms. ### Method N/A (Configuration instruction) ### Endpoint N/A (Configuration instruction) ### Parameters N/A (Configuration instruction) ### Request Example ```javascript // Via JavaScript $('.django-select2').djangoSelect2({ minimumInputLength: 0, placeholder: 'Select an option', // ... other Select2 options }); ``` ```python # Via Django widget attributes from django import forms from django_select2.forms import ModelSelect2MultipleWidget class MyForm(forms.Form): my_field = forms.ModelMultipleChoiceField( widget=ModelSelect2MultipleWidget( model=YourModel, # Replace YourModel with your actual model search_fields=['field_name'], # Replace field_name with actual field attrs={ "data-minimum-input-length": 0, "data-placeholder": "Select an option", "data-close-on-select": "false", # ... other Select2 data attributes } ) ) ``` ### Response N/A (Configuration instruction) ``` -------------------------------- ### Django Template for Book Form Source: https://django-select2.readthedocs.io/en/latest/index A basic HTML template for rendering the Django form, including necessary media CSS and JS, and jQuery for Select2 functionality. ```html Create Book {{ form.media.css }}

Create a new Book

{% csrf_token %} {{ form.as_p }}
{{ form.media.js }} ``` -------------------------------- ### Django-Select2: ModelSelect2Mixin Label From Instance Method Source: https://django-select2.readthedocs.io/en/latest/django_select2 Shows the 'label_from_instance' method in ModelSelect2Mixin, used to customize the display text for each option in the select widget. It takes a model instance and returns a string representation. ```python def label_from_instance(self, obj): """Return option label representation from instance. Can be overridden to change the representation of each choice.""" # Example usage: # class MyWidget(ModelSelect2Widget): # def label_from_instance(obj): # return str(obj.title).upper() # Parameters: # obj: Instance of Django Model. # Returns: Option label. ``` -------------------------------- ### Configure Django Cache for Select2 Source: https://django-select2.readthedocs.io/en/latest/index Sets up a Redis cache backend named 'select2' in Django's settings and configures django-select2 to use it. ```python CACHES = { # … default cache config and others "select2": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/2", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } # Tell select2 which cache configuration to use: SELECT2_CACHE_BACKEND = "select2" ``` -------------------------------- ### Django-Select2 Heavy Widget - HeavySelect2Widget Source: https://django-select2.readthedocs.io/en/latest/django_select2 A Select2 widget with AJAX support that integrates with Django's Cache. It is initialized either by specifying a data_view name or a direct data_url. Media is handled dynamically. ```python class MyWidget(HeavySelect2Widget): data_view = 'my_view_name' class MyForm(forms.Form): my_field = forms.ChoiceField( widget=HeavySelect2Widget( data_url='/url/to/json/response' ) ) @property def media(self): # Construct Media as a dynamic property. # Note: pass ``` -------------------------------- ### JavaScript Initialization Source: https://django-select2.readthedocs.io/en/latest/_sources/django_select2 DjangoSelect2 provides automatic JavaScript initialization and a jQuery plugin for manual control. Include form media in templates and optionally call djangoSelect2() on select fields. ```APIDOC ## JavaScript Initialization ### Description DjangoSelect2 handles automatic initialization of Select2 fields. Provides jQuery plugin for manual initialization and configuration. ### Automatic Initialization Include form media in your template before closing body tag: ```html {{ form.media.js }} ``` ### Manual Initialization For forms inserted after page load or custom initialization: ```javascript $('.django-select2').djangoSelect2(); ``` ### Configuration via JavaScript ```javascript $('.django-select2').djangoSelect2({ minimumInputLength: 0, placeholder: 'Select an option' }); ``` ### Configuration via Django Pass data attributes to widget: ```python attrs={ "data-minimum-input-length": 0, "data-placeholder": "Select an option", "data-close-on-select": "false" } ``` ### Select2 Options See [Select2 Configuration Docs](https://select2.org/configuration/options-api) for complete list of available options. ### Migration Note Replace all `.select2()` invocations with `.djangoSelect2()` for proper initialization. ``` -------------------------------- ### AutoResponseView for Heavy Model Widgets Source: https://django-select2.readthedocs.io/en/latest/django_select2 Details the AutoResponseView, which handles requests from heavy model widgets and returns JSON responses containing search results. ```APIDOC ## AutoResponseView ### Description This view handles AJAX requests from heavy model Select2 widgets, providing paginated results based on search queries. It renders each result using the widget's `result_from_instance` method. ### Method GET ### Endpoint `/select2/` (This endpoint is typically included via `django_select2.urls`) ### Parameters #### Query Parameters - **term** (string) - Optional - The search term entered by the user. - **page** (integer) - Optional - The page number for pagination. ### Request Example N/A (This is a server-side view) ### Response #### Success Response (200) - **results** (list) - A list of dictionaries, where each dictionary represents a search result. - **text** (string) - The display text for the option. - **id** (integer/string) - The value (ID) of the option. - **more** (boolean) - Indicates if there are more results available for the current query. #### Response Example ```json { "results": [ { "text": "Example Option 1", "id": 1 }, { "text": "Example Option 2", "id": 2 } ], "more": true } ``` ``` -------------------------------- ### Django-Select2 Base Mixin - Select2Mixin Source: https://django-select2.readthedocs.io/en/latest/django_select2 The base mixin for all Select2 widgets. It handles rendering necessary data attributes and adding static form media. It defines default CSS classes and theme options. ```python class Select2Mixin(object): css_class_name = 'django-select2' theme = None empty_label = '' @property def i18n_name(self): # Name of the i18n file for the current language. pass def build_attrs(self, base_attrs, extra_attrs=None): # Add select2 data attributes. pass def optgroups(self, name, value, attrs=None): # Add empty option for clearable selects. pass @property def media(self): # Construct Media as a dynamic property. # Note: For more information visit https://docs.djangoproject.com/en/stable/topics/forms/media/#media-as-a-dynamic-property pass ``` -------------------------------- ### Configure Select2 Options with JavaScript Source: https://django-select2.readthedocs.io/en/latest/_sources/django_select2 Demonstrates how to pass Select2 configuration options directly using the DjangoSelect2 jQuery plugin. This allows for dynamic customization of the select input fields in the browser. ```javascript $('.django-select2').djangoSelect2({ minimumInputLength: 0, placeholder: 'Select an option', }); ``` -------------------------------- ### Include django_select2 URLs Source: https://django-select2.readthedocs.io/en/latest/_sources/index Configuration snippet for Django's root URL configuration (urls.py) to include the URLs provided by django_select2. This enables the select2 functionality for views. ```python from django.urls import include, path urlpatterns = [ # other patterns… path("select2/", include("django_select2.urls")), # other patterns… ] ``` -------------------------------- ### Configure Redis Cache Backend for Django Source: https://django-select2.readthedocs.io/en/latest/_sources/index Configuration snippet for Django's settings.py to set up Redis as a cache backend named 'select2'. This backend is used by django-select2 for storing metadata. ```python CACHES = { # … default cache config and others "select2": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/2", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } # Tell select2 which cache configuration to use: SELECT2_CACHE_BACKEND = "select2" ``` -------------------------------- ### Configuration Module Source: https://django-select2.readthedocs.io/en/latest/_sources/django_select2 The django_select2.conf module provides configuration settings for the Select2 integration. This module exposes members that control the behavior and settings of Select2 widgets throughout the application. ```APIDOC ## Configuration Module ### Module django_select2.conf ### Description Provides configuration settings and options for Django Select2 integration. This module contains all configuration members that control Select2 widget behavior and settings. ### Members - Configuration classes and functions for Select2 behavior - Settings for cache, data sources, and widget initialization - Customizable options for Select2 functionality ### Usage ```python from django_select2.conf import * # Access configuration members and settings ``` ``` -------------------------------- ### Django-Select2: ModelSelect2Widget Media Property Source: https://django-select2.readthedocs.io/en/latest/django_select2 Shows the 'media' property for ModelSelect2Widget, which is used for dynamically constructing media assets. This ensures that necessary JavaScript and CSS are loaded for the widget's functionality. ```python class ModelSelect2Widget(ModelSelect2Mixin, HeavySelect2Widget): """Select2 drop in model select widget.""" @property def media(self): """Construct Media as a dynamic property.""" # Note: For more information visit https://docs.djangoproject.com/en/stable/topics/forms/media/#media-as-a-dynamic-property pass ``` -------------------------------- ### Configure Django-Select2 Theme and Internationalization Path Source: https://django-select2.readthedocs.io/en/latest/_modules/django_select2/conf This code demonstrates how to configure the theme and internationalization (i18n) path for Django-Select2. You can set a custom theme name and specify a different base URI for Select2's i18n files, enabling localization for different languages. This is useful for matching your application's style and serving i18n files locally. ```python # Set a custom theme for Select2 SELECT2_THEME = "custom_theme" # Set a custom path for Select2 i18n files SELECT2_I18N_PATH = 'assets/js/i18n' ``` -------------------------------- ### Customize Select2 CSS File Path Source: https://django-select2.readthedocs.io/en/latest/django_select2 Defines the URI for the Select2 CSS file. The default points to Django's shipped version. Customize this in settings.py to use local assets or include additional theme CSS files. Setting it to an empty list will prevent any CSS from being loaded. ```python # Use a local CSS file SELECT2_CSS = ['assets/css/select2.css'] # Include additional theme CSS SELECT2_CSS = [ 'assets/css/select2.css', 'assets/css/select2-theme.css', ] # Disable loading any CSS file SELECT2_CSS = [] ``` -------------------------------- ### Django-Select2 Heavy Mixin - HeavySelect2Mixin Source: https://django-select2.readthedocs.io/en/latest/django_select2 Mixin for Select2 widgets that adds AJAX options and registers the widget with Django's cache. It handles data view configuration and URL retrieval for AJAX requests. Overridable methods for cache registration are provided. ```python class HeavySelect2Mixin(object): data_view = None data_url = None dependent_fields = {} def get_url(self): # Return URL from instance or by reversing `data_view`. pass def build_attrs(self, base_attrs, extra_attrs=None): # Set select2’s AJAX attributes. pass def render(self, *args, **kwargs): # Render widget and register it in Django’s cache. pass def set_to_cache(self): # Add widget object to Django’s cache. # You may need to overwrite this method, to pickle all information that is required to serve your JSON response view. pass ``` -------------------------------- ### Django-Select2: ModelSelect2MultipleWidget Media Property Source: https://django-select2.readthedocs.io/en/latest/django_select2 Illustrates the 'media' property for ModelSelect2MultipleWidget, responsible for managing dynamic media assets. This widget extends ModelSelect2Widget to support multiple selections. ```python class ModelSelect2MultipleWidget(ModelSelect2Mixin, HeavySelect2MultipleWidget): """Select2 drop in model multiple select widget.""" @property def media(self): """Construct Media as a dynamic property.""" # Note: For more information visit https://docs.djangoproject.com/en/stable/topics/forms/media/#media-as-a-dynamic-property pass ``` -------------------------------- ### Initialize Django-Select2 Fields with JavaScript Source: https://django-select2.readthedocs.io/en/latest/django_select2 Shows how to manually initialize Django-Select2 fields using its jQuery plugin. This is useful for forms loaded dynamically or when custom initialization is required. It replaces standard Select2 initializations with the `.djangoSelect2()` method. ```javascript $('.django-select2').djangoSelect2(); ``` -------------------------------- ### Django-Select2: ModelSelect2Mixin Result From Instance Method Source: https://django-select2.readthedocs.io/en/latest/django_select2 Details the 'result_from_instance' method in ModelSelect2Mixin, which defines the dictionary structure returned for each object displayed in the widget's results. This allows for custom data inclusion, such as 'id', 'text', and 'extra_data'. ```python def result_from_instance(self, obj, request): """Return a dictionary representing the object. Can be overridden to change the result returned by `AutoResponseView` for each object.""" # Example usage: # class MyWidget(ModelSelect2Widget): # def result_from_instance(obj, request): # return { # 'id': obj.pk, # 'text': self.label_from_instance(obj), # 'extra_data': obj.extra_data, # } # The request passed in will correspond to the request sent to the `AutoResponseView` by the widget. ``` -------------------------------- ### Django-Select2 Tag Widget - Select2TagWidget Source: https://django-select2.readthedocs.io/en/latest/django_select2 A Select2 widget with tagging support, enabling dynamic creation of options from user input. Includes custom methods for handling data values and option groups, particularly useful for fields like ArrayField. ```python class MyWidget(Select2TagWidget): def value_from_datadict(self, data, files, name): values = super().value_from_datadict(data, files, name) return ",".join(values) def optgroups(self, name, value, attrs=None): values = value[0].split(',') if value[0] else [] selected = set(values) subgroup = [self.create_option(name, v, v, selected, i) for i, v in enumerate(values)] return [(None, subgroup, 0)] @property def media(self): # Construct Media as a dynamic property. # Note: For more information visit https://docs.djangoproject.com/en/stable/topics/forms/media/#media-as-a-dynamic-property pass ``` -------------------------------- ### Select2AdminMixin for Django Admin Autocomplete Source: https://django-select2.readthedocs.io/en/latest/_modules/django_select2/forms A mixin for Django's admin interface that integrates Select2 widgets. It applies a specific theme ('admin-autocomplete') and ensures the necessary Select2 CSS is included, working alongside Django's AutocompleteMixin. ```python class Select2AdminMixin: """Select2 mixin that uses Django's own select template.""" theme = "admin-autocomplete" @property def media(self): css = {**AutocompleteMixin(None, None).media._css} css["screen"].append("django_select2/django_select2.css") ```