# based on the DateSelect widget from django, tested with newforms-admin, need to test with 1.0
class SelectTimeWidget(Widget):
"""
A Widget that splits time input into two <select> boxes.
This also serves as an example of a Widget that has more than one HTML
element and hence implements value_from_datadict.
"""
hour_field = '%s_hour'
minute_field = '%s_minute'
apm_field = '%s_apm'
def __init__(self, attrs=None):
# years is an optional list/tuple of years to use in the "year" select box.
self.attrs = attrs or {}
def render(self, name, value, attrs=None):
hour_val = minute_val = apm_val = None
try:
value = datetime.time(*map(int, value.split(':')))
#value = datetime.date(*map(int, value.split('-')))
#pdb.set_trace()
#year_val, month_val, day_val = value.year, value.month, value.day
if value.hour > 12:
value.hour -= 12
apm_val = 'pm'
else:
hour_val = value.hour
apm_val = 'am'
minute_val = value.minute
except (AttributeError, TypeError, ValueError):
hour_val = '8'
minute_val = apm_val = None
output = []
hour_choices = (
('1','1'),
('2','2'),
('3','3'),
('4','4'),
('5','5'),
('6','6'),
('7','7'),
('8','8'),
('9','9'),
('10','10'),
('11','11'),
('12','12'),
)
select_html = Select(choices=hour_choices).render(self.hour_field % name, hour_val)
output.append(select_html)
minute_choices = (('00','00'), ('15','15'), ('30','30'), ('45','45'))
select_html = Select(choices=minute_choices).render(self.minute_field % name, minute_val)
output.append(select_html)
apm_choices = (('am','AM'), ('pm','PM'))
select_html = Select(choices=apm_choices).render(self.apm_field % name, apm_val)
output.append(select_html)
return mark_safe(u'\n'.join(output))
def value_from_datadict(self, data, files, name):
#y, m, d = data.get(self.year_field % name), data.get(self.month_field % name), data.get(self.day_field % name)
h, m, a = data.get(self.hour_field % name), data.get(self.minute_field % name), data.get(self.apm_field % name)
if a == 'pm':
h = int(h) + 12
if h and m:
return '%s:%s:%s' % (h,m,'00')
#if y and m and d:
# return '%s-%s-%s' % (y, m, d)
return data.get(name, None)
</select>