Skip to content

Commit

Permalink
Enable datetime localization for client
Browse files Browse the repository at this point in the history
- Detect and store client timezone in cookies
- Add TimezoneMiddleware to activate localization based on cookies

Signed-off-by: Keshav Priyadarshi <[email protected]>
  • Loading branch information
keshav-space committed Jan 1, 2025
1 parent b867180 commit 1e32797
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
30 changes: 30 additions & 0 deletions fedcode/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# FederatedCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/federatedcode for support or download.
# See https://aboutcode.org for more information about AboutCode.org OSS projects.
#

import zoneinfo

from django.utils import timezone


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

def __call__(self, request):
try:
# Activate local timezone for user using cookies
tzname = request.COOKIES.get("user_timezone")
if tzname:
timezone.activate(zoneinfo.ZoneInfo(tzname))
else:
timezone.deactivate()
except Exception as e:
timezone.deactivate()

return self.get_response(request)
7 changes: 7 additions & 0 deletions fedcode/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@
</div>

<script src="{% static 'js/notification.js' %}" defer></script>
<script>
// Since django can not determine the client’s time zone automatically.
// Store client's timezone in cookies to enable localization.
// https://docs.djangoproject.com/en/5.1/topics/i18n/timezones/#selecting-the-current-time-zone
const currentTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
document.cookie = "user_timezone=" + currentTimeZone;
</script>
{% block scripts %}
{% endblock %}
</body>
Expand Down
1 change: 1 addition & 0 deletions federatedcode/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
"django.middleware.clickjacking.XFrameOptionsMiddleware",
# OAUTH
"oauth2_provider.middleware.OAuth2TokenMiddleware",
"fedcode.middleware.TimezoneMiddleware",
]

ROOT_URLCONF = "federatedcode.urls"
Expand Down

0 comments on commit 1e32797

Please sign in to comment.