Ticket #3442: grouped_select.diff

File grouped_select.diff, 2.4 KB (added by Thejaswi Puthraya, 17 years ago)

Added the GroupSelect Widget to django.newforms.extras.widgets and added support for unicode and mark_safe

  • django/newforms/extras/widgets.py

     
    44
    55import datetime
    66
     7import copy
     8from itertools import chain
     9
    710from django.newforms.widgets import Widget, Select
    811from django.utils.dates import MONTHS
    912from django.utils.safestring import mark_safe
     13from django.utils.encoding import StrAndUnicode, force_unicode
     14from django.utils.html import escape, conditional_escape
     15from django.newforms.util import flatatt
    1016
    11 __all__ = ('SelectDateWidget',)
     17__all__ = ('SelectDateWidget', 'GroupedSelect')
    1218
    1319class SelectDateWidget(Widget):
    1420    """
     
    5965        if y and m and d:
    6066            return '%s-%s-%s' % (y, m, d)
    6167        return data.get(name, None)
     68
     69class GroupedSelect(Select):
     70    def __init__(self, attrs=None, groups=(), choices=()):
     71        super(GroupedSelect, self).__init__(attrs, choices)
     72        # groups maps from 'group name' to a list of values in that group
     73        # to preserve ordering, it's a list-of-tuples instead of a dict
     74        self.groups = groups
     75
     76    def render(self, name, value, attrs=None, choices=()):
     77        if value is None: value = ''
     78        final_attrs = self.build_attrs(attrs, name=name)
     79        output = [u'<select%s>' % flatatt(final_attrs)]
     80        str_value = force_unicode(value) # Normalize to string.
     81        allchoices = dict([(force_unicode(k), force_unicode(v))
     82            for k, v in chain(self.choices, choices)])
     83        for group_label, members in self.groups:
     84            group_label = force_unicode(group_label)
     85            output.append(u'<optgroup label="%s">' % escape(group_label))
     86            for option_value in members:
     87                option_value = force_unicode(option_value)
     88                try:
     89                    option_label = allchoices[option_value]
     90                except KeyError:
     91                    continue # silently ignore missing elements from the group
     92                selected_html = (option_value == str_value) and u' selected="selected"' or ''
     93                output.append(u'<option value="%s"%s>%s</option>' % (escape(option_value), selected_html, escape(option_label)))
     94            output.append(u'</optgroup>')
     95        output.append(u'</select>')
     96        return mark_safe(u'\n'.join(output))
Back to Top