Login

Accurate Timing MultiField & MultiWidget (w. milliseconds)

Author:
jokull
Posted:
February 18, 2010
Language:
Python
Version:
1.1
Score:
0 (after 0 ratings)

Suitable for use with DecimalField. Handy for accurate timing input (think sports, racing etc.).

 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
class TimeWidget(forms.MultiWidget):
    """Input accurate timing. IntegerFields for hours, minutes, seconds, milliseconds."""
    
    NUM_FIELDS = 4 # Hours, Minutes, Seconds, Milliseconds
    
    def __init__(self, attrs=None):
        widgets = [forms.TextInput()] * self.NUM_FIELDS
        super(TimeWidget, self).__init__(widgets, attrs)
        
    def format_output(self, widgets):
        widgets.insert(1, ' : ')
        widgets.insert(3, ' : ')
        widgets.insert(5, ' . ')
        return mark_safe(''.join(widgets))
        
    def decompress(self, value):
        if value:
            return ('%d' % (value/3600), '%02d' % (value%3600/60), 
                    '%02d' % (value%3600%60), '%03d' % (value%1*1000))
        return [None] * self.NUM_FIELDS


class TimeField(forms.MultiValueField):
    """Input accurate timing. Interface with models.DecimalField for great success."""
    
    LABELS  = ['Hours', 'Minutes', 'Seconds', 'Milliseconds'] 
    SECONDS = [ 60*60,   60,        1,         0.001]
    widget = TimeWidget()
    
    def __init__(self, *args, **kwargs):
        fields = [forms.CharField(label=label) for label in self.LABELS]
        super(TimeField, self).__init__(fields, *args, **kwargs)
    
    def compress(self, value):
        if value:
            from operator import add, mul
            return str(reduce(add, 
                        map(lambda x: mul(*x), 
                            zip(map(float, value), self.SECONDS))))
        return None
 

More like this

  1. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 4 weeks ago
  2. Python Django CRUD Example Tutorial by tuts_station 1 month, 2 weeks ago
  3. Browser-native date input field by kytta 2 months, 4 weeks ago
  4. Generate and render HTML Table by LLyaudet 3 months, 1 week ago
  5. My firs Snippets by GutemaG 3 months, 1 week ago

Comments

Please login first before commenting.