Opened 4 years ago

Closed 4 years ago

Last modified 4 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 Changed 4 years ago by zauddelig

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 4 years ago by zauddelig (previous) (diff)

comment:2 Changed 4 years ago by Tim Graham

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 Changed 4 years ago by Tim Graham <timograham@…>

Resolution: fixed
Status: newclosed

In 262d4db8:

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

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

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