From 722e330518df8ce4e2c2084ab453adab0660dc46 Mon Sep 17 00:00:00 2001 From: Erik Stein Date: Tue, 19 Feb 2019 11:46:36 +0100 Subject: [PATCH] Mock datetime for preview. --- shared/utils/conf.py | 4 ++++ shared/utils/preview.py | 25 +++++++++++++++++++++++++ shared/utils/timezone.py | 14 +++++++++++--- 3 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 shared/utils/preview.py diff --git a/shared/utils/conf.py b/shared/utils/conf.py index 94492e7..1f01071 100644 --- a/shared/utils/conf.py +++ b/shared/utils/conf.py @@ -4,3 +4,7 @@ USE_TRANSLATABLE_FIELDS = ( getattr(settings, 'CONTENT_PLUGINS_USE_TRANSLATABLE_FIELDS', False) or getattr(settings, 'USE_TRANSLATABLE_FIELDS', False) ) + + +USE_PREVIEW_DATETIME = getattr(settings, 'USE_PREVIEW_DATETIME', False) +# You also have to set PREVIEW_DATETIME = datetime(...) diff --git a/shared/utils/preview.py b/shared/utils/preview.py new file mode 100644 index 0000000..082742f --- /dev/null +++ b/shared/utils/preview.py @@ -0,0 +1,25 @@ +from django.conf import settings +from django.utils import timezone + +from .conf import USE_PREVIEW_DATETIME +from .timezone import smart_default_tz + + +class datetime(timezone.datetime): + @classmethod + def now(klass): + if USE_PREVIEW_DATETIME: + if settings.DEBUG_PREVIEW_DATETIME: + now = timezone.datetime(*settings.DEBUG_PREVIEW_DATETIME) + else: + # TODO Get preview datetime from request user + now = timezone.now() + if settings.USE_TZ: + now = smart_default_tz(now) + else: + now = timezone.now() + return now + + @classmethod + def today(klass): + return klass.now().date() diff --git a/shared/utils/timezone.py b/shared/utils/timezone.py index 0372fd6..06f6c0a 100644 --- a/shared/utils/timezone.py +++ b/shared/utils/timezone.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import unicode_literals -# Erik Stein , 2015 """ Django and Timezones @@ -17,6 +14,8 @@ A sample Django application illustrating some time zone traps for the unwary. """ +import datetime +from django.conf import settings from django.utils import timezone @@ -28,3 +27,12 @@ def smart_default_tz(datetime_value): datetime_value = timezone.make_aware(datetime_value, timezone=timezone.get_default_timezone()) return timezone.localtime(datetime_value, timezone.get_default_timezone()) + +def timezone_today(): + """ + Return the current date in the current time zone. + """ + if settings.USE_TZ: + return timezone.localdate() + else: + return datetime.date.today()