As an exercise, I'm trying to create my own django widget for a 24-hour clock. The widget will be a MultiWidget - a selection field for each field.
I'm trying to keep track of documents online (seemingly sparse) and look at the Pro Django book, but I can't figure out what it is. Am I on the right track? I can save my data from the form, but when I pre-fill the form, the form has no previous values.
It seems that the problem is that the argument of the method “value” of the decompression method () 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 call the widget as:
arrival_time = forms.TimeField(label="Arrival Time", required=False, widget=MilitaryTimeWidget())