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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.