As an exercise I am trying to create a custom django widget for a 24 hour clock. The widget will is a MultiWidget - a select box for each field.
I am trying to follow docs online (kinda sparse) and looking at the Pro Django book, but I can't seem to figure it out. Am I on the right track? I can save my data from the form, but when I prepopulate the form, the form doesn't have the previous values.
It seems the issue is that the decompress() methods 'value' argument is always empty, so I have nothing to interpret.
from django.forms import widgets
import datetime
class MilitaryTimeWidget(widgets.MultiWidget):
"""
A widget that displays 24 hours time selection.
"""
def __init__(self, attrs=None):
hours = [ (i, "%02d" %(i)) for i in range(0, 24) ]
minutes = [ (i, "%02d" %(i)) for i in range(0, 60) ]
_widgets = (
widgets.Select(attrs=attrs, choices=hours),
widgets.Select(attrs=attrs, choices=minutes),
)
super(MilitaryTimeWidget, self).__init__(_widgets, attrs)
def decompress(self, value):
print "******** %s" %value
if value:
return [int(value.hour), int(value.minute)]
return [None, None]
def value_from_datadict(self, data, files, name):
hour = data.get("%s_0" %name, None)
minute = data.get("%s_1" %name, None)
if hour and minute:
hour = int(hour)
minute = int(minute)
return datetime.time(hour=hour, minute=minute)
return None
In my form, I am calling the widget like:
arrival_time = forms.TimeField(label="Arrival Time", required=False, widget=MilitaryTimeWidget())