DurationField
This class provides a field for handling duration values, converting input strings or time delta objects into Python timedelta instances. It includes built-in validation to ensure inputs are formatted correctly and fall within the supported range of days. The class also handles the preparation of values for display by converting timedelta objects into standardized duration strings.
Attributes
| Attribute | Type | Description |
|---|---|---|
| default_error_messages | dict = {"invalid": "Enter a valid duration.", "overflow": "The number of days must be between {min_days} and {max_days}."} | A dictionary of error message templates used to notify users when input is not a valid duration or exceeds the supported day range. |
Methods
prepare_value()
@classmethod
def prepare_value(
value: any
) - > string
Converts a timedelta object into a standardized duration string format for display or serialization.
Parameters
| Name | Type | Description |
|---|---|---|
| value | any | The duration value to be formatted, typically a datetime.timedelta instance. |
Returns
| Type | Description |
|---|---|
string | A formatted duration string if the input is a timedelta, otherwise the original value. |
to_python()
@classmethod
def to_python(
value: any
) - > datetime.timedelta
Parses a string or numeric input into a datetime.timedelta object, validating that the value is within acceptable day ranges.
Parameters
| Name | Type | Description |
|---|---|---|
| value | any | The raw input value to be converted into a duration object. |
Returns
| Type | Description |
|---|---|
datetime.timedelta | A timedelta object representing the parsed duration, or None if the input is empty. |