Skip to content

Commit

Permalink
Merge pull request #5326 from akvo/fix-invalid-project-created-at-date
Browse files Browse the repository at this point in the history
Work around for invalid project.created_at timezone
  • Loading branch information
zuhdil authored Apr 19, 2024
2 parents 0e03f13 + 4d26282 commit 7f42981
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
11 changes: 10 additions & 1 deletion akvo/rest/serializers/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from timeout_decorator import timeout

from akvo.rsr.models import Project, ProjectUpdate, IndicatorPeriodData
from akvo.utils import get_thumbnail
from akvo.utils import get_thumbnail, make_safe_timezone_aware_date
from akvo.rsr.models.project_thumbnail import get_cached_thumbnail
from akvo.rsr.usecases.iati_validation import schedule_iati_activity_validation
from . import OrganisationBasicSerializer
Expand Down Expand Up @@ -80,6 +80,7 @@ class ProjectSerializer(BaseRSRSerializer):
iati_profile_url = serializers.SerializerMethodField()
path = serializers.SerializerMethodField()
uuid = serializers.ReadOnlyField()
created_at = serializers.SerializerMethodField()

class Meta:
model = Project
Expand Down Expand Up @@ -136,6 +137,14 @@ def get_iati_profile_url(self, obj):
def get_path(self, project: Project):
return str(project.path)

def get_created_at(self, project: Project):
"""
This is a work around to silence the "Invalid datetime for the timezone
Europe/Stockholm" which has appeared several times and not yet known
why.
"""
return make_safe_timezone_aware_date(project.created_at)

def update(self, project: Project, validated_data: dict):
if "contributes_to_project" in validated_data:
parent = validated_data['contributes_to_project']
Expand Down
16 changes: 15 additions & 1 deletion akvo/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

# utility functions for RSR
from collections import namedtuple
from datetime import datetime
import hashlib
import inspect
import json
Expand Down Expand Up @@ -569,3 +568,18 @@ def __init__(self, real):

def __getattr__(self, attr):
return getattr(self._real, attr)


def make_safe_timezone_aware_date(d):
'''
If datetime is naive and is an invalid datetime of current timezone,
then assume datetime is in UTC and convert it to a datetime of current
timezone.
'''
if not timezone.is_naive(d):
return d
try:
return timezone.make_aware(d, timezone.get_current_timezone())
except pytz.InvalidTimeError:
date_utc = timezone.make_aware(d, timezone.utc)
return date_utc.astimezone(timezone.get_current_timezone())

0 comments on commit 7f42981

Please sign in to comment.