Skip to content

Commit 1e32797

Browse files
committed
Enable datetime localization for client
- Detect and store client timezone in cookies - Add TimezoneMiddleware to activate localization based on cookies Signed-off-by: Keshav Priyadarshi <[email protected]>
1 parent b867180 commit 1e32797

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

fedcode/middleware.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#
2+
# Copyright (c) nexB Inc. and others. All rights reserved.
3+
# FederatedCode is a trademark of nexB Inc.
4+
# SPDX-License-Identifier: Apache-2.0
5+
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
6+
# See https://github.com/nexB/federatedcode for support or download.
7+
# See https://aboutcode.org for more information about AboutCode.org OSS projects.
8+
#
9+
10+
import zoneinfo
11+
12+
from django.utils import timezone
13+
14+
15+
class TimezoneMiddleware:
16+
def __init__(self, get_response):
17+
self.get_response = get_response
18+
19+
def __call__(self, request):
20+
try:
21+
# Activate local timezone for user using cookies
22+
tzname = request.COOKIES.get("user_timezone")
23+
if tzname:
24+
timezone.activate(zoneinfo.ZoneInfo(tzname))
25+
else:
26+
timezone.deactivate()
27+
except Exception as e:
28+
timezone.deactivate()
29+
30+
return self.get_response(request)

fedcode/templates/base.html

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@
2828
</div>
2929

3030
<script src="{% static 'js/notification.js' %}" defer></script>
31+
<script>
32+
// Since django can not determine the client’s time zone automatically.
33+
// Store client's timezone in cookies to enable localization.
34+
// https://docs.djangoproject.com/en/5.1/topics/i18n/timezones/#selecting-the-current-time-zone
35+
const currentTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
36+
document.cookie = "user_timezone=" + currentTimeZone;
37+
</script>
3138
{% block scripts %}
3239
{% endblock %}
3340
</body>

federatedcode/settings.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@
9090
"django.middleware.clickjacking.XFrameOptionsMiddleware",
9191
# OAUTH
9292
"oauth2_provider.middleware.OAuth2TokenMiddleware",
93+
"fedcode.middleware.TimezoneMiddleware",
9394
]
9495

9596
ROOT_URLCONF = "federatedcode.urls"

0 commit comments

Comments
 (0)