Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Source code clean-ups.

Some imports have moved which might break existing code. Will be documented
in CHANGELOG (once I make it)
  • Loading branch information...
commit 3c9a30f6656c29d609266ec385f5e51ee885474d 1 parent ba4485e
@brosner authored
View
8 timezones/decorators.py
@@ -1,17 +1,19 @@
+from django.conf import settings
+from django.utils.encoding import smart_str
import pytz
-from django.utils.encoding import smart_str
-from django.conf import settings
+
default_tz = pytz.timezone(getattr(settings, "TIME_ZONE", "UTC"))
+
+
def localdatetime(field_name):
def get_datetime(instance):
return getattr(instance, field_name)
def set_datetime(instance, value):
return setattr(instance, field_name, value)
-
def make_local_property(get_tz):
def get_local(instance):
tz = get_tz(instance)
View
39 timezones/fields.py
@@ -1,30 +1,30 @@
-
-from django.db import models
from django.conf import settings
-from django.utils.encoding import smart_unicode, smart_str
+from django.db import models
from django.db.models import signals
+from django.utils.encoding import smart_unicode, smart_str
+
+import pytz
from timezones import forms
-from timezones.utils import coerce_timezone_value
+from timezones.utils import coerce_timezone_value, validate_timezone_max_length
+
-import pytz
MAX_TIMEZONE_LENGTH = getattr(settings, "MAX_TIMEZONE_LENGTH", 100)
default_tz = pytz.timezone(getattr(settings, "TIME_ZONE", "UTC"))
-assert reduce(lambda x, y: x and (len(y) <= MAX_TIMEZONE_LENGTH),
- forms.ALL_TIMEZONE_CHOICES, True), \
- "timezones.fields.TimeZoneField MAX_TIMEZONE_LENGTH is too small"
-
class TimeZoneField(models.CharField):
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
- defaults = {"max_length": MAX_TIMEZONE_LENGTH,
- "default": settings.TIME_ZONE,
- "choices": forms.PRETTY_TIMEZONE_CHOICES}
+ validate_timezone_max_length(MAX_TIMEZONE_LENGTH, zones.ALL_TIMEZONE_CHOICES)
+ defaults = {
+ "max_length": MAX_TIMEZONE_LENGTH,
+ "default": settings.TIME_ZONE,
+ "choices": forms.PRETTY_TIMEZONE_CHOICES
+ }
defaults.update(kwargs)
return super(TimeZoneField, self).__init__(*args, **defaults)
@@ -75,16 +75,18 @@ def __init__(self, verbose_name=None, name=None, timezone=None, **kwargs):
else:
self.timezone = timezone
super(LocalizedDateTimeField, self).__init__(verbose_name, name, **kwargs)
-
+
def formfield(self, **kwargs):
defaults = {"form_class": forms.LocalizedDateTimeField}
if (not isinstance(self.timezone, basestring) and str(self.timezone) in pytz.all_timezones_set):
defaults["timezone"] = str(self.timezone)
defaults.update(kwargs)
return super(LocalizedDateTimeField, self).formfield(**defaults)
-
+
def get_db_prep_save(self, value):
- "Returns field's value prepared for saving into a database."
+ """
+ Returns field's value prepared for saving into a database.
+ """
## convert to settings.TIME_ZONE
if value is not None:
if value.tzinfo is None:
@@ -92,9 +94,11 @@ def get_db_prep_save(self, value):
else:
value = value.astimezone(default_tz)
return super(LocalizedDateTimeField, self).get_db_prep_save(value)
-
+
def get_db_prep_lookup(self, lookup_type, value):
- "Returns field's value prepared for database lookup."
+ """
+ Returns field's value prepared for database lookup.
+ """
## convert to settings.TIME_ZONE
if value.tzinfo is None:
value = default_tz.localize(value)
@@ -102,6 +106,7 @@ def get_db_prep_lookup(self, lookup_type, value):
value = value.astimezone(default_tz)
return super(LocalizedDateTimeField, self).get_db_prep_lookup(lookup_type, value)
+
def prep_localized_datetime(sender, **kwargs):
for field in sender._meta.fields:
if not isinstance(field, LocalizedDateTimeField) or field.timezone is None:
View
16 timezones/forms.py
@@ -1,23 +1,17 @@
+from django import forms
+from django.conf import settings
import pytz
-import datetime
-
-from django.conf import settings
-from django import forms
+from timezones import zones
from timezones.utils import adjust_datetime_to_timezone, coerce_timezone_value
-ALL_TIMEZONE_CHOICES = tuple(zip(pytz.all_timezones, pytz.all_timezones))
-COMMON_TIMEZONE_CHOICES = tuple(zip(pytz.common_timezones, pytz.common_timezones))
-PRETTY_TIMEZONE_CHOICES = []
-for tz in pytz.common_timezones:
- now = datetime.datetime.now(pytz.timezone(tz))
- PRETTY_TIMEZONE_CHOICES.append((tz, "(GMT%s) %s" % (now.strftime("%z"), tz)))
+
class TimeZoneField(forms.TypedChoiceField):
def __init__(self, *args, **kwargs):
if not "choices" in kwargs:
- kwargs["choices"] = PRETTY_TIMEZONE_CHOICES
+ kwargs["choices"] = zones.PRETTY_TIMEZONE_CHOICES
kwargs["coerce"] = coerce_timezone_value
super(TimeZoneField, self).__init__(*args, **kwargs)
View
17 timezones/utils.py
@@ -1,9 +1,9 @@
+from django.conf import settings
+from django.core.exceptions import ValidationError
+from django.utils.encoding import smart_str
import pytz
-from django.conf import settings
-from django.utils.encoding import smart_str
-from django.core.exceptions import ValidationError
def localtime_for_timezone(value, timezone):
"""
@@ -12,6 +12,7 @@ def localtime_for_timezone(value, timezone):
"""
return adjust_datetime_to_timezone(value, settings.TIME_ZONE, timezone)
+
def adjust_datetime_to_timezone(value, from_tz, to_tz=None):
"""
Given a ``datetime`` object adjust it according to the from_tz timezone
@@ -25,8 +26,16 @@ def adjust_datetime_to_timezone(value, from_tz, to_tz=None):
value = from_tz.localize(value)
return value.astimezone(pytz.timezone(smart_str(to_tz)))
+
def coerce_timezone_value(value):
try:
return pytz.timezone(value)
except pytz.UnknownTimeZoneError:
- raise ValidationError("Unknown timezone")
+ raise ValidationError("Unknown timezone")
+
+
+def validate_timezone_max_length(max_length, zones):
+ def reducer(x, y):
+ return x and (len(y) <= max_length)
+ if not reduce(reducer, zones, True):
+ raise Exception("timezones.fields.TimeZoneField MAX_TIMEZONE_LENGTH is too small")
View
13 timezones/zones.py
@@ -0,0 +1,13 @@
+from datetime import datetime
+
+import pytz
+
+
+
+ALL_TIMEZONE_CHOICES = tuple(zip(pytz.all_timezones, pytz.all_timezones))
+COMMON_TIMEZONE_CHOICES = tuple(zip(pytz.common_timezones, pytz.common_timezones))
+PRETTY_TIMEZONE_CHOICES = []
+
+for tz in pytz.common_timezones:
+ now = datetime.now(pytz.timezone(tz))
+ PRETTY_TIMEZONE_CHOICES.append((tz, "(GMT%s) %s" % (now.strftime("%z"), tz)))
Please sign in to comment.
Something went wrong with that request. Please try again.