The SplitTimeField and the corresponding widget SplitDateTimeWidget show two select boxes with one for hour from 0 to 23 and the other showing minutes 0,15,30 and 45 (can be customized very easily).
Usage:
class TestForm(forms.Form):
start_time = SplitTimeField(widget=SplitTimeWidget)
end_time = SplitTimeField(widget=SplitTimeWidget)
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 | class SplitTimeField(forms.MultiValueField):
"""
Field written to accept two fields Hour Field and Time Field
and combine them into TimeField.
"""
default_error_messages = {
'invalid_time': _(u'Enter a valid time.'),
}
def __init__(self, *args, **kwargs):
errors = self.default_error_messages.copy()
if 'error_messages' in kwargs:
errors.update(kwargs['error_messages'])
fields = (
forms.CharField(error_messages={'invalid': errors['invalid_time']}),
forms.CharField(error_messages={'invalid': errors['invalid_time']}),
)
super(SplitTimeField, self).__init__(fields, *args, **kwargs)
def compress(self, data_list):
if data_list:
# Raise a validation error if time or date is empty
# (possible if SplitDateTimeField has required=False).
if data_list[0] in (None, '') or data_list[1] in (None, ''):
raise forms.ValidationError(self.error_messages['invalid_time'])
return datetime.time(int(data_list[0]),int(data_list[1]))
return None
class SplitTimeWidget(forms.MultiWidget):
"""
Widget written to split widget into hours and minutes.
"""
def __init__(self, attrs=None):
widgets = (
forms.Select(attrs=attrs, choices=([(hour,hour) for hour in range(0,24)])), \
forms.Select(attrs=attrs, choices=([(minute, str(minute).zfill(2)) for minute in [0,15,30,45]]))
)
super(SplitTimeWidget, self).__init__(widgets, attrs)
def decompress(self, value):
if value:
return [value.hour, value.minute]
return [None, None]
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.