Login

SplitTimeField

Author:
theju
Posted:
February 8, 2008
Language:
Python
Version:
1.2
Tags:
forms field widget
Score:
2 (after 2 ratings)

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

  1. ImageField for admin with thumbnail by semente 6 years, 2 months ago
  2. Plugin Framework by Gulopine 7 years, 7 months ago
  3. DropDownMultiple widget by marinho 7 years, 3 months ago
  4. Binding signals to abstract models by andreterra 3 years, 3 months ago
  5. Widget for CommaSeparatedIntegerField with pre-defined choices by rudyryk 5 years, 2 months ago

Comments

Please login first before commenting.