Skip to content

Commit

Permalink
Rewrite Select2ListField
Browse files Browse the repository at this point in the history
  • Loading branch information
jpic committed Nov 26, 2021
1 parent d57a87b commit 8de5b22
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 38 deletions.
48 changes: 16 additions & 32 deletions src/dal_select2/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,21 @@
from django.forms import ChoiceField


class ChoiceCallable:
def __init__(self, choices):
self.choices = choices

def __call__(self):
result = []
choices = self.choices() if callable(self.choices) else self.choices
for choice in choices:
if isinstance(choice, (list, tuple)):
result.append(choice)
else:
result.append((choice, choice))
return result


class Select2ListChoiceField(ChoiceField):
"""Allows a list of values to be used with a ChoiceField.
Expand All @@ -17,38 +32,7 @@ def __init__(self, choice_list=None, required=True, widget=None,
.. py:param choice_list: The list to use to generate choices or a
function that returns a list.
"""
choice_list = choice_list or []

if callable(choice_list):
if (
all(isinstance(el, list) for el in choice_list())
and len(choice_list()) > 0
):
choices = (
lambda: [(value, text) for [value, text] in choice_list()])
elif (
all(isinstance(el, tuple) for el in choice_list())
and len(choice_list()) > 0
):
choices = (
lambda: [(value, text) for (value, text) in choice_list()])
else:
choices = (
lambda: [(choice, choice) for choice in choice_list()])

else:
if (
all(isinstance(el, list) for el in choice_list)
and len(choice_list) > 0
):
choices = [(value, text) for [value, text] in choice_list]
elif (
all(isinstance(el, tuple) for el in choice_list)
and len(choice_list) > 0
):
choices = [(value, text) for (value, text) in choice_list]
else:
choices = [(choice, choice) for choice in choice_list]
choices = ChoiceCallable(choice_list)

super(Select2ListChoiceField, self).__init__(
choices=choices, required=required, widget=widget, label=label,
Expand Down
8 changes: 2 additions & 6 deletions test_project/select2_list/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,11 @@ def test_init(self):
def test_init_lists(self):
field = autocomplete.Select2ListChoiceField(
choice_list=self.choice_list_lists)
six.assertCountEqual(
self, field.choices,
[(value, text) for [value, text] in self.choice_list_lists])
six.assertCountEqual(self, field.choices, self.choice_list_lists)

field = autocomplete.Select2ListChoiceField(
choice_list=self.get_choice_list_lists)
six.assertCountEqual(
self, field.choices,
[(value, text) for [value, text] in self.choice_list_lists])
six.assertCountEqual(self, field.choices, self.choice_list_lists)

def test_init_tuples(self):
field = autocomplete.Select2ListChoiceField(
Expand Down

0 comments on commit 8de5b22

Please sign in to comment.