Kevin Wetzels avatar Kevin Wetzels committed 5f258a6

Add license and readme

Comments (0)

Files changed (18)

+Copyright (c) 2011, Kevin Wetzels
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+    Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+    Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+================
+django-stdfields
+================
+
+Fields I wish were standard in Django. At the moment this is limited to the
+``MinutesField``.
+
+Contents
+========
+
+MinutesField
+------------
+Is an extension of Django's standard ``django.forms.IntegerField``.
+
+This field will accept values for a duration in minutes in the formats 
+``hh:mm`` or ``h.fraction``, similar to the way BaseCamp allows you to specify 
+your time spent on a task as either '8:30' or ``8.5``. In the latter case only 
+``8.25``, ``8.5``, ``8.50`` and ``8.75`` are considered valid inputs.
+
+Example
+=======
+
+    # models.py
+    class Task(models.Model):
+        time_spent = models.IntegerField()
+
+    # forms.py
+    from stdfields.forms import MinutesField
+    
+    from models import Task
+    
+    class TaskForm(forms.Form):
+        time_spent = MinutesField(label='How long did it take?')
+        
+        class Meta:
+            model = Task

Empty file removed.

forms.py

-# -*- coding: utf-8 -*-
-from __future__ import division
-import re
-
-from django import forms
-from django.utils.encoding import smart_str
-
-from widgets import MinutesWidget
-
-class MinutesField(forms.IntegerField):
-    
-    widget = MinutesWidget
-    
-    def clean(self, value):
-        value = smart_str(value).strip()
-        match = re.search(r'^(\d+):(\d{1,2})$', value)
-        if match:
-            groups = match.groups()
-            hours = int(groups[0])
-            minutes = int(groups[1])
-            if minutes > 59:
-                raise forms.ValidationError(self.error_messages['invalid'])
-            value = (hours * 60) + minutes
-        else:
-            value = value.replace(',', '.')
-            if '.' in value:
-                parts = value.split('.')
-                try:
-                    hours = int(parts[0])
-                    fraction = int(parts[1])
-                    if not fraction in (5, 25, 50, 75):
-                        raise forms.ValidationError(self.error_messages['invalid'])
-                    if fraction == 5:
-                        fraction = 50
-                    value = int((hours * 60) + (60 / 100 * fraction))
-                except (ValueError, TypeError):
-                    raise forms.ValidationError(self.error_messages['invalid'])
-        return super(MinutesField, self).clean(value)

models.py

-from django.db import models
-
-# Create your models here.

Empty file added.

stdfields/forms.py

+# -*- coding: utf-8 -*-
+from __future__ import division
+import re
+
+from django import forms
+from django.utils.encoding import smart_str
+
+from widgets import MinutesWidget
+
+class MinutesField(forms.IntegerField):
+    
+    widget = MinutesWidget
+    
+    def clean(self, value):
+        value = smart_str(value).strip()
+        match = re.search(r'^(\d+):(\d{1,2})$', value)
+        if match:
+            groups = match.groups()
+            hours = int(groups[0])
+            minutes = int(groups[1])
+            if minutes > 59:
+                raise forms.ValidationError(self.error_messages['invalid'])
+            value = (hours * 60) + minutes
+        else:
+            value = value.replace(',', '.')
+            if '.' in value:
+                parts = value.split('.')
+                try:
+                    hours = int(parts[0])
+                    fraction = int(parts[1])
+                    if not fraction in (5, 25, 50, 75):
+                        raise forms.ValidationError(self.error_messages['invalid'])
+                    if fraction == 5:
+                        fraction = 50
+                    value = int((hours * 60) + (60 / 100 * fraction))
+                except (ValueError, TypeError):
+                    raise forms.ValidationError(self.error_messages['invalid'])
+        return super(MinutesField, self).clean(value)

stdfields/models.py

+from django.db import models
+
+# Create your models here.
Add a comment to this file

stdfields/templatetags/__init__.py

Empty file added.

stdfields/templatetags/stdfieldstags.py

+# -*- coding: utf-8 -*-
+from __future__ import absolute_import
+from django import template
+
+from stdfields.widgets import format_minutes
+
+register = template.Library()
+
+@register.filter 
+def minutes(value):
+    return format_minutes(value)

stdfields/tests.py

+# -*- coding: utf-8 -*-
+"""
+Test cases for MinutesField and MinutesWidget.
+"""
+from django.test import TestCase
+from django.forms import ValidationError
+
+from stdfields.forms import MinutesField
+from stdfields.widgets import MinutesWidget
+
+class MinutesFieldTest(TestCase):
+    
+    def test_minutes_field(self):
+        f = MinutesField()
+        self.assertEqual(121, f.clean(121))
+        self.assertEqual(121, f.clean('2:01'))
+        self.assertEqual(121, f.clean('2:1'))
+        self.assertEqual(150, f.clean('2.5'))
+        self.assertEqual(150, f.clean('2,5'))
+        self.assertEqual(150, f.clean('2.50'))
+        self.assertEqual(150, f.clean('2.50.120'))
+        self.assertEqual(135, f.clean('2.25'))
+        self.assertEqual(165, f.clean('2.75'))
+        minutes = 480
+        for i in range(60):
+            self.assertEqual(minutes + i, f.clean('8:%d' % (i)))
+        
+    def test_minutes_field_invalid(self):
+        f = MinutesField()
+        self._should_raise_validation_error(f, '2:60')
+        self._should_raise_validation_error(f, 'x:60')
+        self._should_raise_validation_error(f, 'x:y')
+        self._should_raise_validation_error(f, '2;30')
+        self._should_raise_validation_error(f, '2;30')
+        
+    def _should_raise_validation_error(self, f, value):
+        try:
+            f.clean(value)
+            self.fail('%s should raise a ValidationError' % (value))
+        except ValidationError:
+            pass
+
+
+class MinutesWidgetTest(TestCase):
+    
+    def test_minutes_widget(self):
+        w = MinutesWidget()
+        self.assertEqual(w.render('hi', '121'), '<input type="text" name="hi" value="2:01" />')
+        self.assertEqual(w.render('hi', '2:1'), '<input type="text" name="hi" value="2:1" />')
+        self.assertEqual(w.render('hi', '2:60'), '<input type="text" name="hi" value="2:60" />')
+        self.assertEqual(w.render('hi', '493'), '<input type="text" name="hi" value="8:13" />')

stdfields/views.py

+# Create your views here.

stdfields/widgets.py

+# -*- coding: utf-8 -*-
+from django.forms.widgets import TextInput
+
+def format_minutes(value):
+    if value is None or value == '':
+        return u''
+    try:
+        value = int(value)
+    except ValueError:
+        return value
+    divided = MinutesWidget.divide(value)
+    return u'%d:%02d' % divided
+
+class MinutesWidget(TextInput):
+    
+    def _format_value(self, value):
+        return format_minutes(value)
+        
+    @classmethod
+    def divide(cls, total):
+        if total <= 0:
+            return (0, 0)
+        hours = 0 if total <= 60 else total / 60
+        return (hours, total - (hours * 60))
Add a comment to this file

templatetags/__init__.py

Empty file removed.

templatetags/stdfieldstags.py

-# -*- coding: utf-8 -*-
-from __future__ import absolute_import
-from django import template
-
-from stdfields.widgets import format_minutes
-
-register = template.Library()
-
-@register.filter 
-def minutes(value):
-    return format_minutes(value)

tests.py

-# -*- coding: utf-8 -*-
-"""
-Test cases for MinutesField and MinutesWidget.
-"""
-from django.test import TestCase
-from django.forms import ValidationError
-
-from stdfields.forms import MinutesField
-from stdfields.widgets import MinutesWidget
-
-class MinutesFieldTest(TestCase):
-    
-    def test_minutes_field(self):
-        f = MinutesField()
-        self.assertEqual(121, f.clean(121))
-        self.assertEqual(121, f.clean('2:01'))
-        self.assertEqual(121, f.clean('2:1'))
-        self.assertEqual(150, f.clean('2.5'))
-        self.assertEqual(150, f.clean('2,5'))
-        self.assertEqual(150, f.clean('2.50'))
-        self.assertEqual(150, f.clean('2.50.120'))
-        self.assertEqual(135, f.clean('2.25'))
-        self.assertEqual(165, f.clean('2.75'))
-        minutes = 480
-        for i in range(60):
-            self.assertEqual(minutes + i, f.clean('8:%d' % (i)))
-        
-    def test_minutes_field_invalid(self):
-        f = MinutesField()
-        self._should_raise_validation_error(f, '2:60')
-        self._should_raise_validation_error(f, 'x:60')
-        self._should_raise_validation_error(f, 'x:y')
-        self._should_raise_validation_error(f, '2;30')
-        self._should_raise_validation_error(f, '2;30')
-        
-    def _should_raise_validation_error(self, f, value):
-        try:
-            f.clean(value)
-            self.fail('%s should raise a ValidationError' % (value))
-        except ValidationError:
-            pass
-
-
-class MinutesWidgetTest(TestCase):
-    
-    def test_minutes_widget(self):
-        w = MinutesWidget()
-        self.assertEqual(w.render('hi', '121'), '<input type="text" name="hi" value="2:01" />')
-        self.assertEqual(w.render('hi', '2:1'), '<input type="text" name="hi" value="2:1" />')
-        self.assertEqual(w.render('hi', '2:60'), '<input type="text" name="hi" value="2:60" />')
-        self.assertEqual(w.render('hi', '493'), '<input type="text" name="hi" value="8:13" />')

views.py

-# Create your views here.

widgets.py

-# -*- coding: utf-8 -*-
-from django.forms.widgets import TextInput
-
-def format_minutes(value):
-    if value is None or value == '':
-        return u''
-    try:
-        value = int(value)
-    except ValueError:
-        return value
-    divided = MinutesWidget.divide(value)
-    return u'%d:%02d' % divided
-
-class MinutesWidget(TextInput):
-    
-    def _format_value(self, value):
-        return format_minutes(value)
-        
-    @classmethod
-    def divide(cls, total):
-        if total <= 0:
-            return (0, 0)
-        hours = 0 if total <= 60 else total / 60
-        return (hours, total - (hours * 60))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.