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
66
67
68
69
70
71
|
from django import newforms as forms
from django.newforms.util import flatatt, StrAndUnicode, smart_unicode
from itertools import chain
__all__ = ('VolSelect')
class RadioInput(StrAndUnicode):
"An object used by RadioFieldRenderer that represents a single <input type='radio'>."
def __init__(self, name, value, attrs, choice, index):
self.name, self.value = name, value
self.attrs = attrs
self.choice_value = smart_unicode(choice[0])
self.choice_label = smart_unicode(choice[1])
self.index = index
def __unicode__(self):
return u'<label>%s %s</label>' % (self.tag(), self.choice_label)
def is_checked(self):
return self.value == self.choice_value
def tag(self):
if self.attrs.has_key('id'):
self.attrs['id'] = '%s_%s' % (self.attrs['id'], self.index)
final_attrs = dict(self.attrs, type='radio', name=self.name, value=self.choice_value)
if self.is_checked():
final_attrs['checked'] = 'checked'
return u'<input%s />' % flatatt(final_attrs)
class RadioFieldRenderer(StrAndUnicode):
"An object used by RadioSelect to enable customization of radio widgets."
def __init__(self, name, value, attrs, choices):
self.name, self.value, self.attrs = name, value, attrs
self.choices = choices
def __iter__(self):
for i, choice in enumerate(self.choices):
yield RadioInput(self.name, self.value, self.attrs.copy(), choice, i)
def __getitem__(self, idx):
choice = self.choices[idx] # Let the IndexError propogate
return RadioInput(self.name, self.value, self.attrs.copy(), choice, idx)
def __unicode__(self):
"Outputs a <ul> for this set of radio fields."
return u'<ul>\n%s\n</ul>' % u'\n'.join([u'<li>%s</li>' % w for w in self])
class VolInput(RadioInput):
"An object used by RadioFieldRenderer that represents a single <input type='radio'>."
def __unicode__(self):
return u'<td class="input">%s</td>' % self.tag()
class VolFieldRenderer(RadioFieldRenderer):
def __iter__(self):
for i, choice in enumerate(self.choices):
yield VolInput(self.name, self.value, self.attrs.copy(), choice, i)
def __getitem__(self, idx):
choice = self.choices[idx] # Let the IndexError propogate
return VolInput(self.name, self.value, self.attrs.copy(), choice, idx)
def __unicode__(self):
"Outputs the set of radio fields."
return u'\n'.join([u'%s' % w for w in self])
class VolSelect(forms.RadioSelect):
def render(self, name, value, attrs=None, choices=()):
"Returns a VolFieldRenderer instance rather than a Unicode string."
if value is None: value = ''
str_value = smart_unicode(value)
attrs = attrs or {}
return VolFieldRenderer(name, str_value, attrs, list(chain(self.choices, choices)))
|