Login

Choice Field and Select Widget With Optional Optgroups

Author:
leahculver
Posted:
April 24, 2007
Language:
Python
Version:
.96
Score:
10 (after 10 ratings)

Renders an select field with some optgroups. Some options can be outside the optgroup(s).

The options and labels should be in a tuple with ((label, choices),) where choices is a tuple ((key, value), (key2, value2)). If a label is null or blank, the options will not belong to an opt group.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from django import newforms as forms

# widget for select with optional opt groups
# modified from ticket 3442
# not sure if it's better but it doesn't force all options to be grouped

# Example:
# groceries = ((False, (('milk','milk'), (-1,'eggs'))), ('fruit', ((0,'apple'), (1,'orange'))), ('', (('yum','beer'), )),) 
# grocery_list = GroupedChoiceField(choices=groceries)

# Renders:
# <select name="grocery_list" id="id_grocery_list">
#   <option value="milk">milk</option>
#   <option value="-1">eggs</option>
#   <optgroup label="fruit">
#     <option value="0">apple</option>
#     <option value="1">orange</option>
#   </optgroup>
#   <option value="yum">beer</option>
# </select>

class GroupedSelect(forms.Select): 
    def render(self, name, value, attrs=None, choices=()):
        from django.utils.html import escape
        from django.newforms.util import flatatt, smart_unicode 
        if value is None: value = '' 
        final_attrs = self.build_attrs(attrs, name=name) 
        output = [u'<select%s>' % flatatt(final_attrs)] 
        str_value = smart_unicode(value)
        for group_label, group in self.choices: 
            if group_label: # should belong to an optgroup
                group_label = smart_unicode(group_label) 
                output.append(u'<optgroup label="%s">' % escape(group_label)) 
            for k, v in group:
                option_value = smart_unicode(k)
                option_label = smart_unicode(v) 
                selected_html = (option_value == str_value) and u' selected="selected"' or ''
                output.append(u'<option value="%s"%s>%s</option>' % (escape(option_value), selected_html, escape(option_label))) 
            if group_label:
                output.append(u'</optgroup>') 
        output.append(u'</select>') 
        return u'\n'.join(output)

# field for grouped choices, handles cleaning of funky choice tuple
class GroupedChoiceField(forms.ChoiceField):
    def __init__(self, choices=(), required=True, widget=GroupedSelect, label=None, initial=None, help_text=None):
        super(forms.ChoiceField, self).__init__(required, widget, label, initial, help_text)
        self.choices = choices
        
    def clean(self, value):
        """
        Validates that the input is in self.choices.
        """
        value = super(forms.ChoiceField, self).clean(value)
        if value in (None, ''):
            value = u''
        value = forms.util.smart_unicode(value)
        if value == u'':
            return value
        valid_values = []
        for group_label, group in self.choices:
            valid_values += [str(k) for k, v in group]
        if value not in valid_values:
            raise ValidationError(gettext(u'Select a valid choice. That choice is not one of the available choices.'))
        return value

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

gkelly (on April 24, 2007):

Awesome. I'm already putting this one to use.

#

leahculver (on April 25, 2007):

I've updated the snippet and added a custom field that will verify the data is clean.

#

IanSparks (on January 26, 2008):

Version of Django I'm using (Trunc Rev 7028) you'll want to use mark_safe on the return from GroupedSelect.render

return mark_safe(u'\n'.join(output)) #<-- THIS!

Without the mark_safe you'll get escaped HTML from this.

#

MichaelSchade (on June 9, 2008):

Thanks lanSparks for the tip, but for others reading this, they need to remember to add this to the top of their file:

from django.utils.safestring import mark_safe

Otherwise that snippet that lanSparks provided will not work.

Thanks a bunch for this code, it helped me tremendously!

#

thierrystiegler (on November 12, 2008):

Just a little notice with Django 1.0, switch :

from django import newforms as forms

to:

from django import forms

Thank you for this snippet, was really helpfull !

#

wwu.housing (on June 7, 2010):

Using Django 1.2 you want to switch:

from django.newforms.util import flatatt, smart_unicode

or

from django.forms.util import flatatt, smart_unicode

to:

from django.utils.encoding import smart_unicode

#

Please login first before commenting.