diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 623e72e0a..7079e3332 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -29,7 +29,11 @@ from django.utils.encoding import is_protected_type, smart_str from django.utils.formats import localize_input, sanitize_separators from django.utils.ipv6 import clean_ipv6_address from django.utils.translation import gettext_lazy as _ -from pytz.exceptions import InvalidTimeError + +try: + import pytz +except ImportError: + pytz = None from rest_framework import ISO_8601 from rest_framework.exceptions import ErrorDetail, ValidationError @@ -1148,8 +1152,10 @@ class DateTimeField(Field): if not valid_datetime(dt): self.fail('make_aware', timezone=field_timezone) return dt - except InvalidTimeError: - self.fail('make_aware', timezone=field_timezone) + except Exception as e: + if pytz and isinstance(e, pytz.exceptions.InvalidTimeError): + self.fail('make_aware', timezone=field_timezone) + raise e elif (field_timezone is None) and timezone.is_aware(value): return timezone.make_naive(value, datetime.timezone.utc) return value diff --git a/setup.py b/setup.py index 533ffa97f..6afd5e05e 100755 --- a/setup.py +++ b/setup.py @@ -83,7 +83,7 @@ setup( author_email='tom@tomchristie.com', # SEE NOTE BELOW (*) packages=find_packages(exclude=['tests*']), include_package_data=True, - install_requires=["django>=3.0", "pytz", 'backports.zoneinfo;python_version<"3.9"'], + install_requires=["django>=3.0", 'backports.zoneinfo;python_version<"3.9"'], python_requires=">=3.6", zip_safe=False, classifiers=[ diff --git a/tests/test_fields.py b/tests/test_fields.py index bcf388441..50d9d7793 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -9,7 +9,12 @@ from enum import auto from unittest.mock import patch import pytest -import pytz + +try: + import pytz +except ImportError: + pytz = None + from django.core.exceptions import ValidationError as DjangoValidationError from django.db.models import IntegerChoices, TextChoices from django.http import QueryDict @@ -1604,15 +1609,16 @@ class TestPytzNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues): } outputs = {} - class MockTimezone(pytz.BaseTzInfo): - @staticmethod - def localize(value, is_dst): - raise pytz.InvalidTimeError() + if pytz: + class MockTimezone(pytz.BaseTzInfo): + @staticmethod + def localize(value, is_dst): + raise pytz.InvalidTimeError() - def __str__(self): - return 'America/New_York' + def __str__(self): + return 'America/New_York' - field = serializers.DateTimeField(default_timezone=MockTimezone()) + field = serializers.DateTimeField(default_timezone=MockTimezone()) @patch('rest_framework.utils.timezone.datetime_ambiguous', return_value=True)