Permalink
Browse files

TimeZoneFormField

  • Loading branch information...
1 parent 2d7848a commit 9871fc3642adde28391b071d2e472e6b924c779a @mfogel committed Dec 27, 2012
Showing with 42 additions and 4 deletions.
  1. +2 −1 timezone_field/__init__.py
  2. +13 −0 timezone_field/forms.py
  3. +27 −3 timezone_field/tests.py
@@ -1,3 +1,4 @@
-from .fields import TimeZoneField # noqa
+from .fields import TimeZoneField # noqa
+from .forms import TimeZoneFormField # noqa
__version__ = '0.3.2'
View
@@ -0,0 +1,13 @@
+import pytz
+from django import forms
+
+
+class TimeZoneFormField(forms.TypedChoiceField):
+ def __init__(self, *args, **kwargs):
+ defaults = {
+ 'coerce': lambda val: pytz.timezone(val),
+ 'choices': [(tz, tz) for tz in pytz.all_timezones],
+ 'empty_value': None,
+ }
+ defaults.update(kwargs)
+ super(TimeZoneFormField, self).__init__(*args, **defaults)
View
@@ -5,11 +5,11 @@
from django.db import models
from django.test import TestCase
-from . import TimeZoneField
+from . import TimeZoneField, TimeZoneFormField
-PST = 'America/Los_Angeles' # instance of pytz.tzinfo.DstTzInfo
-GMT = 'Etc/GMT' # instance of pytz.tzinfo.StaticTzInfo
+PST = 'America/Los_Angeles' # pytz.tzinfo.DstTzInfo
+GMT = 'Etc/GMT' # pytz.tzinfo.StaticTzInfo
UTC = 'UTC' # pytz.UTC singleton
INVALID_TZ = 'ogga booga'
@@ -22,11 +22,35 @@ class TestModel(models.Model):
tz_blank_null = TimeZoneField(blank=True, null=True)
+class TestForm(forms.Form):
+ tz = TimeZoneFormField()
+ tz2 = TimeZoneFormField(required=False)
+
+
class TestModelForm(forms.ModelForm):
class Meta:
model = TestModel
+class TimeZoneFormFieldTestCase(TestCase):
+
+ def test_valid1(self):
+ form = TestForm({'tz': PST})
+ self.assertTrue(form.is_valid())
+ self.assertEqual(form.cleaned_data['tz'], pytz.timezone(PST))
+ self.assertEqual(form.cleaned_data['tz2'], None)
+
+ def test_valid2(self):
+ form = TestForm({'tz': GMT, 'tz2': UTC})
+ self.assertTrue(form.is_valid())
+ self.assertEqual(form.cleaned_data['tz'], pytz.timezone(GMT))
+ self.assertEqual(form.cleaned_data['tz2'], pytz.UTC)
+
+ def test_invalid_invalid_str(self):
+ form = TestForm({'tz': INVALID_TZ})
+ self.assertFalse(form.is_valid())
+
+
class TimeZoneFieldModelFormTestCase(TestCase):
def test_valid1(self):

0 comments on commit 9871fc3

Please sign in to comment.