Move unpack_grouped_choices() to utilities.choices

This commit is contained in:
Jeremy Stretch 2020-01-15 09:36:39 -05:00
parent b538495a29
commit 826f4d313d
3 changed files with 37 additions and 41 deletions

View File

@ -1,6 +1,3 @@
from utilities.forms import unpack_grouped_choices
class ChoiceSetMeta(type):
"""
Metaclass for ChoiceSet
@ -46,3 +43,38 @@ class ChoiceSet(metaclass=ChoiceSetMeta):
(id, slug) for slug, id in cls.LEGACY_MAP.items()
])
return legacy_map.get(legacy_id)
def unpack_grouped_choices(choices):
"""
Unpack a grouped choices hierarchy into a flat list of two-tuples. For example:
choices = (
('Foo', (
(1, 'A'),
(2, 'B')
)),
('Bar', (
(3, 'C'),
(4, 'D')
))
)
becomes:
choices = (
(1, 'A'),
(2, 'B'),
(3, 'C'),
(4, 'D')
)
"""
unpacked_choices = []
for key, value in choices:
if isinstance(value, (list, tuple)):
# Entered an optgroup
for optgroup_key, optgroup_value in value:
unpacked_choices.append((optgroup_key, optgroup_value))
else:
unpacked_choices.append((key, value))
return unpacked_choices

View File

@ -9,6 +9,7 @@ from django.conf import settings
from django.contrib.postgres.forms.jsonb import JSONField as _JSONField, InvalidJSONInput
from mptt.forms import TreeNodeMultipleChoiceField
from .choices import unpack_grouped_choices
from .constants import *
from .validators import EnhancedURLValidator
@ -119,43 +120,6 @@ def add_blank_choice(choices):
return ((None, '---------'),) + tuple(choices)
def unpack_grouped_choices(choices):
"""
Unpack a grouped choices hierarchy into a flat list of two-tuples. For example:
choices = (
('Foo', (
(1, 'A'),
(2, 'B')
)),
('Bar', (
(3, 'C'),
(4, 'D')
))
)
becomes:
choices = (
(1, 'A'),
(2, 'B'),
(3, 'C'),
(4, 'D')
)
"""
unpacked_choices = []
for key, value in choices:
if key == 1300:
breakme = True
if isinstance(value, (list, tuple)):
# Entered an optgroup
for optgroup_key, optgroup_value in value:
unpacked_choices.append((optgroup_key, optgroup_value))
else:
unpacked_choices.append((key, value))
return unpacked_choices
#
# Widgets
#

View File

@ -7,7 +7,7 @@ from django.utils.html import strip_tags
from django.utils.safestring import mark_safe
from markdown import markdown
from utilities.forms import unpack_grouped_choices
from utilities.choices import unpack_grouped_choices
from utilities.utils import foreground_color