Skip to content

Commit

Permalink
Fix #565 -- Support empty_label on ModelSelect fields.
Browse files Browse the repository at this point in the history
  • Loading branch information
codingjoe committed Aug 26, 2019
1 parent 8bd7f72 commit dca7dbc
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
11 changes: 10 additions & 1 deletion django_select2/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,16 @@ 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}
if self.is_required:
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)
Expand Down Expand Up @@ -208,6 +210,7 @@ def __init__(self, attrs=None, choices=(), **kwargs):
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:
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
8 changes: 8 additions & 0 deletions tests/test_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,14 @@ def test_custom_to_field_name(self):
form = forms.GroupieForm(instance=groupie)
assert '<option value="Take That" selected>TAKE THAT</option>' 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):

Expand Down

0 comments on commit dca7dbc

Please sign in to comment.