Fix #565 -- Support empty_label on ModelSelect fields.

This commit is contained in:
Johannes Hoppe 2019-08-26 17:02:43 +02:00
parent 8bd7f7209f
commit dca7dbc5d1
3 changed files with 19 additions and 2 deletions

View file

@ -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.

View file

@ -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:

View file

@ -412,6 +412,14 @@ class TestModelSelect2Mixin(TestHeavySelect2Mixin):
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):