Skip to content

Commit 52f4139

Browse files
Properly handle OverflowError in DurationField deserialization (#8042)
Related: https://github.com/django/django/pull/8870/files
1 parent 9e328a9 commit 52f4139

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

rest_framework/fields.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1329,6 +1329,7 @@ class DurationField(Field):
13291329
'invalid': _('Duration has wrong format. Use one of these formats instead: {format}.'),
13301330
'max_value': _('Ensure this value is less than or equal to {max_value}.'),
13311331
'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
1332+
'overflow': _('The number of days must be between {min_days} and {max_days}.'),
13321333
}
13331334

13341335
def __init__(self, **kwargs):
@@ -1347,7 +1348,10 @@ def __init__(self, **kwargs):
13471348
def to_internal_value(self, value):
13481349
if isinstance(value, datetime.timedelta):
13491350
return value
1350-
parsed = parse_duration(str(value))
1351+
try:
1352+
parsed = parse_duration(str(value))
1353+
except OverflowError:
1354+
self.fail('overflow', min_days=datetime.timedelta.min.days, max_days=datetime.timedelta.max.days)
13511355
if parsed is not None:
13521356
return parsed
13531357
self.fail('invalid', format='[DD] [HH:[MM:]]ss[.uuuuuu]')

tests/test_fields.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1642,10 +1642,14 @@ class TestDurationField(FieldValues):
16421642
'08:01': datetime.timedelta(minutes=8, seconds=1),
16431643
datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123): datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123),
16441644
3600: datetime.timedelta(hours=1),
1645+
'-999999999 00': datetime.timedelta(days=-999999999),
1646+
'999999999 00': datetime.timedelta(days=999999999),
16451647
}
16461648
invalid_inputs = {
16471649
'abc': ['Duration has wrong format. Use one of these formats instead: [DD] [HH:[MM:]]ss[.uuuuuu].'],
16481650
'3 08:32 01.123': ['Duration has wrong format. Use one of these formats instead: [DD] [HH:[MM:]]ss[.uuuuuu].'],
1651+
'-1000000000 00': ['The number of days must be between -999999999 and 999999999.'],
1652+
'1000000000 00': ['The number of days must be between -999999999 and 999999999.'],
16491653
}
16501654
outputs = {
16511655
datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123): '3 08:32:01.000123',

0 commit comments

Comments
 (0)