Opened 9 years ago

Closed 9 years ago

Last modified 9 years ago

#24897 closed Bug (fixed)

Choices longer than 1 day don't work with DurationField

Reported by: zauddelig Owned by: nobody
Component: Forms Version: 1.8
Severity: Normal Keywords: DurationField
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: yes Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

When one tries to use DurationField with choices and a time span longer than a day the field will always raise a ValidationError.

choices = (timedelta(days=7), "one week")

The problem is in the to_python method wich calls django.utils.dateparse.parse_duration this methond use the following regex:

standard_duration_re = re.compile(
    r'^'
    r'(?:(?P<days>-?\d+) )?'
    r'((?:(?P<hours>\d+):)(?=\d+:\d+))?'
    r'(?:(?P<minutes>\d+):)?'
    r'(?P<seconds>\d+)'
    r'(?:\.(?P<microseconds>\d{1,6})\d{0,6})?'
    r'$'
)

But is not standard in the view that we are using timedelta objects, whose default rapresentation is : %d days, %h:%m:%s. So I propose to change the regex in with the following:

 standard_duration_re = re.compile(
    r'^'
    r'(?:(?P<days>-?\d+) (days, )?)?'
    r'((?:(?P<hours>\d+):)(?=\d+:\d+))?'
    r'(?:(?P<minutes>\d+):)?'
    r'(?P<seconds>\d+)'
    r'(?:\.(?P<microseconds>\d{1,6})\d{0,6})?'
    r'$'
)

Change History (4)

comment:1 by zauddelig, 9 years ago

EDIT:
I was thinking that this:

choices = (format(timedelta(days=7)).replace("days, ",""), "one week")

would've work but it get blocked at Field.validation level, at that time the value is already checked against a timedelta

Last edited 9 years ago by zauddelig (previous) (diff)

comment:2 by Tim Graham, 9 years ago

Needs tests: set
Summary: Choices don't really work with DurationFieldChoices longer than 1 day don't work with DurationField
Triage Stage: UnreviewedAccepted

comment:3 by Tim Graham <timograham@…>, 9 years ago

Resolution: fixed
Status: newclosed

In 262d4db8:

Fixed #24897 -- Allowed using choices longer than 1 day with DurationField

comment:4 by Tim Graham <timograham@…>, 9 years ago

In 7f92b6e:

[1.8.x] Fixed #24897 -- Allowed using choices longer than 1 day with DurationField

Backport of 262d4db8c4c849b0fdd84550fb96472446cf90df from master

Note: See TracTickets for help on using tickets.
Back to Top