Login

Accurate Timing MultiField & MultiWidget (w. milliseconds)

Author:
jokull
Posted:
February 18, 2010
Language:
Python
Version:
1.1
Tags:
forms multiwidget multifield
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. Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 5 months ago
  2. Crispy Form by sourabhsinha396 5 months, 3 weeks ago
  3. ReadOnlySelect by mkoistinen 6 months, 1 week ago
  4. Verify events sent to your webhook endpoints by santos22 7 months ago
  5. Django Language Middleware by agusmakmun 7 months, 2 weeks ago

Comments

Please login first before commenting.