Skip to content

Commit 29a2e3c

Browse files
committed
Add Select2 mixin that uses Django's own select template
1 parent b858953 commit 29a2e3c

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

django_select2/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@
99
"""
1010
from django import get_version
1111

12-
if get_version() < '3.2':
12+
if get_version() < "3.2":
1313
default_app_config = "django_select2.apps.Select2AppConfig"

django_select2/forms.py

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@
5454

5555
import django
5656
from django import forms
57-
from django.contrib.admin.widgets import SELECT2_TRANSLATIONS
57+
from django.contrib.admin.widgets import SELECT2_TRANSLATIONS, AutocompleteMixin
5858
from django.core import signing
5959
from django.db.models import Q
6060
from django.forms.models import ModelChoiceIterator
@@ -65,7 +65,9 @@
6565
from .conf import settings
6666

6767
if django.VERSION < (4, 0):
68-
from django.contrib.admin.utils import lookup_needs_distinct as lookup_spawns_duplicates
68+
from django.contrib.admin.utils import (
69+
lookup_needs_distinct as lookup_spawns_duplicates,
70+
)
6971
else:
7072
from django.contrib.admin.utils import lookup_spawns_duplicates
7173

@@ -79,6 +81,9 @@ class Select2Mixin:
7981
form media.
8082
"""
8183

84+
css_class_name = "django-select2"
85+
theme = None
86+
8287
empty_label = ""
8388

8489
def __init__(self, *args, **kwargs):
@@ -90,7 +95,7 @@ def build_attrs(self, base_attrs, extra_attrs=None):
9095
default_attrs = {
9196
"lang": self.i18n_name,
9297
"data-minimum-input-length": 0,
93-
"data-theme": settings.SELECT2_THEME,
98+
"data-theme": self.theme or settings.SELECT2_THEME,
9499
}
95100
if self.is_required:
96101
default_attrs["data-allow-clear"] = "false"
@@ -102,9 +107,9 @@ def build_attrs(self, base_attrs, extra_attrs=None):
102107
attrs = super().build_attrs(default_attrs, extra_attrs=extra_attrs)
103108

104109
if "class" in attrs:
105-
attrs["class"] += " django-select2"
110+
attrs["class"] += " " + self.css_class_name
106111
else:
107-
attrs["class"] = "django-select2"
112+
attrs["class"] = self.css_class_name
108113
return attrs
109114

110115
def optgroups(self, name, value, attrs=None):
@@ -137,6 +142,20 @@ def media(self):
137142
)
138143

139144

145+
class Select2AdminMixin:
146+
"""Select2 mixin that uses Django's own select template."""
147+
148+
css_class_name = "admin-autocomplete"
149+
theme = "admin-autocomplete"
150+
151+
@property
152+
def media(self):
153+
return forms.Media(
154+
js=Select2Mixin.media.js,
155+
css=AutocompleteMixin.media.css,
156+
)
157+
158+
140159
class Select2TagMixin:
141160
"""Mixin to add select2 tag functionality."""
142161

0 commit comments

Comments
 (0)