Skip to content

Commit

Permalink
Re-configure timezones for API and Admin
Browse files Browse the repository at this point in the history
Use UTC as Django default timezone so that Django Rest Framework will
use it for the API endpoints, but override the timezone in Django Admin
to still be Europe/Helsinki with a middleware.
  • Loading branch information
suutari-ai committed Dec 12, 2017
1 parent 5760537 commit adb4231
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
31 changes: 31 additions & 0 deletions parkkihubi/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import contextlib
from functools import lru_cache

from django.conf import settings
from django.urls import reverse
from django.utils import timezone

# No-op context manager
#
# Usable like the one coming in Python 3.7, see
# https://github.com/python/cpython/commit/0784a2e5b174d2dbf7b144d480559e650c5cf64c
nullcontext = contextlib.ExitStack


class AdminTimezoneMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
tz_overrider = nullcontext()
if request.path.startswith(get_admin_url_path_prefix()):
admin_tz = getattr(settings, 'ADMIN_TIME_ZONE', None)
if admin_tz:
tz_overrider = timezone.override(admin_tz)
with tz_overrider:
return self.get_response(request)


@lru_cache()
def get_admin_url_path_prefix():
return reverse('admin:index')
6 changes: 4 additions & 2 deletions parkkihubi/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,11 @@
##############
# Middleware #
##############
MIDDLEWARE_CLASSES = [
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'parkkihubi.middleware.AdminTimezoneMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
Expand Down Expand Up @@ -133,7 +134,8 @@
# Languages & Localization #
############################
LANGUAGE_CODE = 'en'
TIME_ZONE = 'Europe/Helsinki'
TIME_ZONE = 'UTC'
ADMIN_TIME_ZONE = 'Europe/Helsinki'
USE_I18N = True
USE_L10N = True
USE_TZ = True
Expand Down

0 comments on commit adb4231

Please sign in to comment.