Skip to content

Commit

Permalink
Fix nested choices (optgroups)
Browse files Browse the repository at this point in the history
  • Loading branch information
sergei-maertens committed Apr 3, 2016
1 parent c1cd905 commit 982be73
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
28 changes: 24 additions & 4 deletions sniplates/templatetags/sniplates.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,9 +268,30 @@ def nested_widget(parser, token):
return NestedWidget(widget, nodelist, kwargs, asvar)


class ChoiceWrapper(namedtuple('ChoiceWrapper', 'value display')):
class ChoiceWrapper(object):

def __init__(self, value, display):
self.value = force_text(value)
self._display = display

def __repr__(self):
return 'ChoiceWrapper(value=%s, display=%s)' % (self.value, self.display)

def __iter__(self):
yield self.value
yield self.display

def is_group(self):
return isinstance(self.display, (list, tuple))
return isinstance(self._display, (list, tuple))

@property
def display(self):
"""
When dealing with optgroups, ensure that the value is properly force_text'd.
"""
if not self.is_group():
return self._display
return ((force_text(k), v) for k, v in self._display)


class FieldExtractor(dict):
Expand Down Expand Up @@ -322,9 +343,8 @@ def choices(self):
c = self.form_field.field.choices
if not c:
return c

return tuple(
ChoiceWrapper(value=force_text(k), display=v)
ChoiceWrapper(value=k, display=v)
for k, v in self.form_field.field.choices
)

Expand Down
12 changes: 12 additions & 0 deletions tests/test_widgets_django.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ def test_widgets_bound(self):
'text': ['Lorem ipsum...'],
'checkbox': [True],
'select': ['22'],
'optgroup_select': ['22'],
'null_boolean_select': [False],
'select_multiple': ['11', '22', 1],
'radio_select': ['11'],
Expand Down Expand Up @@ -195,6 +196,16 @@ def test_widgets_bound(self):
<option value="11">b</option>
<option value="22" selected>c</option>
</select>''',
'optgroup_select': '''
<select id="id_optgroup_select" name="optgroup_select">
<optgroup label="label1">
<option value="1">a</option>
<option value="11">b</option>
</optgroup>
<optgroup label="label2">
<option value="22" selected>c</option>
</optgroup>
</select>''',
'null_boolean_select': '''
<select id="id_null_boolean_select" name="null_boolean_select">
<option value="1">Unknown</option>
Expand Down Expand Up @@ -240,6 +251,7 @@ def test_widgets_bound(self):
self.assertInHTML(expected['checkbox'], output)

self.assertInHTML(expected['select'], output)
self.assertInHTML(expected['optgroup_select'], output)
self.assertInHTML(expected['null_boolean_select'], output)
self.assertInHTML(expected['select_multiple'], output)
self.assertInHTML(expected['radio_select'], output)
Expand Down

0 comments on commit 982be73

Please sign in to comment.