|
12 | 12 | from rest_framework.compat import (
|
13 | 13 | EmailValidator, MinValueValidator, MaxValueValidator,
|
14 | 14 | MinLengthValidator, MaxLengthValidator, URLValidator, OrderedDict,
|
15 |
| - unicode_repr, unicode_to_repr |
| 15 | + unicode_repr, unicode_to_repr, parse_duration, duration_string, |
16 | 16 | )
|
17 | 17 | from rest_framework.exceptions import ValidationError
|
18 | 18 | from rest_framework.settings import api_settings
|
@@ -1003,6 +1003,29 @@ def to_representation(self, value):
|
1003 | 1003 | return value.strftime(self.format)
|
1004 | 1004 |
|
1005 | 1005 |
|
| 1006 | +class DurationField(Field): |
| 1007 | + default_error_messages = { |
| 1008 | + 'invalid': _('Duration has wrong format. Use one of these formats instead: {format}.'), |
| 1009 | + } |
| 1010 | + |
| 1011 | + def __init__(self, *args, **kwargs): |
| 1012 | + if parse_duration is None: |
| 1013 | + raise NotImplementedError( |
| 1014 | + 'DurationField not supported for django versions prior to 1.8') |
| 1015 | + return super(DurationField, self).__init__(*args, **kwargs) |
| 1016 | + |
| 1017 | + def to_internal_value(self, value): |
| 1018 | + if isinstance(value, datetime.timedelta): |
| 1019 | + return value |
| 1020 | + parsed = parse_duration(value) |
| 1021 | + if parsed is not None: |
| 1022 | + return parsed |
| 1023 | + self.fail('invalid', format='[DD] [HH:[MM:]]ss[.uuuuuu]') |
| 1024 | + |
| 1025 | + def to_representation(self, value): |
| 1026 | + return duration_string(value) |
| 1027 | + |
| 1028 | + |
1006 | 1029 | # Choice types...
|
1007 | 1030 |
|
1008 | 1031 | class ChoiceField(Field):
|
|
0 commit comments