diff --git a/django_select2/forms.py b/django_select2/forms.py index b12cb0b..c650557 100644 --- a/django_select2/forms.py +++ b/django_select2/forms.py @@ -70,6 +70,8 @@ class Select2Mixin: form media. """ + empty_label = '' + def build_attrs(self, base_attrs, extra_attrs=None): """Add select2 data attributes.""" default_attrs = {'data-minimum-input-length': 0} @@ -77,7 +79,7 @@ class Select2Mixin: default_attrs['data-allow-clear'] = 'false' else: default_attrs['data-allow-clear'] = 'true' - default_attrs['data-placeholder'] = '' + default_attrs['data-placeholder'] = self.empty_label default_attrs.update(base_attrs) attrs = super().build_attrs(default_attrs, extra_attrs=extra_attrs) @@ -208,6 +210,7 @@ class HeavySelect2Mixin: widget could be dependent on a country. Key is a name of a field in a form. Value is a name of a field in a model (used in `queryset`). + """ self.choices = choices if attrs is not None: @@ -339,6 +342,12 @@ class ModelSelect2Mixin: max_results = 25 """Maximal results returned by :class:`.AutoResponseView`.""" + @property + def empty_label(self): + if isinstance(self.choices, ModelChoiceIterator): + return self.choices.field.empty_label + return '' + def __init__(self, *args, **kwargs): """ Overwrite class parameters if passed as keyword arguments. diff --git a/tests/conftest.py b/tests/conftest.py index 6c46557..c13923a 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -21,7 +21,7 @@ def random_name(n): @pytest.yield_fixture(scope='session') def driver(): chrome_options = webdriver.ChromeOptions() - chrome_options.headless = False + chrome_options.headless = True try: b = webdriver.Chrome(options=chrome_options) except WebDriverException as e: diff --git a/tests/test_forms.py b/tests/test_forms.py index 53e8d34..797dfd4 100644 --- a/tests/test_forms.py +++ b/tests/test_forms.py @@ -412,6 +412,14 @@ class TestModelSelect2Mixin(TestHeavySelect2Mixin): form = forms.GroupieForm(instance=groupie) assert '' in form.as_p() + def test_empty_label(self, db): + # Empty options is only required for single selects + # https://select2.github.io/options.html#allowClear + single_select = self.form.fields['primary_genre'] + single_select.empty_label = 'Hello World' + assert single_select.required is False + assert 'data-placeholder="Hello World"' in single_select.widget.render('primary_genre', None) + class TestHeavySelect2TagWidget(TestHeavySelect2Mixin):