Skip to content

Commit

Permalink
Serializer field handle empty string
Browse files Browse the repository at this point in the history
Closes #86
  • Loading branch information
mfogel committed Jun 18, 2023
1 parent 61f4958 commit 7c1b537
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
6 changes: 6 additions & 0 deletions tests/test_serializer_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ def test_invalid_str(TimeZoneSerializer, invalid_tz):
assert not serializer.is_valid()


# https://github.com/mfogel/django-timezone-field/issues/86
def test_empty_str(TimeZoneSerializer, invalid_tz):
serializer = TimeZoneSerializer(data={"tz": ""})
assert not serializer.is_valid()


def test_valid(TimeZoneSerializer, pst, pst_tz):
serializer = TimeZoneSerializer(data={"tz": pst})
assert serializer.is_valid()
Expand Down
13 changes: 8 additions & 5 deletions timezone_field/rest_framework.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,19 @@ def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

def to_internal_value(self, data):
data_str = force_str(data)
if self.use_pytz:
try:
return pytz.timezone(force_str(data))
return pytz.timezone(data_str)
except pytz.UnknownTimeZoneError:
self.fail("invalid")
else:
try:
return ZoneInfo(force_str(data))
except ZoneInfoNotFoundError:
self.fail("invalid")
if data_str:
try:
return ZoneInfo(data_str)
except ZoneInfoNotFoundError:
pass
self.fail("invalid")

def to_representation(self, value):
return str(value)

0 comments on commit 7c1b537

Please sign in to comment.