Opened 8 years ago

Closed 8 years ago

Last modified 8 years ago

#26104 closed Bug (fixed)

forms.DurationField raise a TypeError when passing it a number

Reported by: xialvjun Owned by: Sasha Gaevsky
Component: Forms Version: 1.9
Severity: Normal Keywords: forms, TypeError
Cc: django@… Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

from django.test import TestCase
from django import forms

class JieDuanModePartForm(forms.Form):
    duration = forms.DurationField()

class JieDuanModeFormTestCase(TestCase):

    def test_data(self):
        data = {'duration': 10800}
        form = JieDuanModePartForm(data=data)
        valid = form.is_valid()
        print(valid)
        print(form.cleaned_data)

code above raise a TypeError...

in forms/fields.py class DurationField method to_python it use:
value = parse_duration(value)
but if wrap it with try block:

        try:
            value = parse_duration(value)
        except TypeError as e:
            raise ValidationError(self.error_messages['invalid'], code='invalid')

things may be better...

Or just value = parse_duration(str(value))

Change History (7)

comment:1 by Keryn Knight, 8 years ago

Cc: django@… added

Chiming in: I suggested xialvjun open this, as I believe it's inconsistent with at least some other fields, even though in the naive case all GET/POST data is stringy, other fields have afforded using real, typed dicts, either from JSON deserialization or just as dictionary validation.

Specifically, the following fields already catch TypeError (gracefully, I think) by a quick glance at the source:

  • IntegerField (#24229 is related)
  • FloatField
  • BaseTemporalField (which DurationField notably is not, though it is notionally related; #18982)
  • TypedChoiceField (for obvious reasons)
  • TypedMultipleChoiceField (as above)
  • ModelChoiceField (#22808)
  • ModelMultipleChoiceField (#22808; partially the 1.7.3 DoS vector IIRC; and #21568 looks related?)

comment:2 by Simon Charette, 8 years ago

Triage Stage: UnreviewedAccepted

comment:3 by Sasha Gaevsky, 8 years ago

Owner: changed from nobody to Sasha Gaevsky
Status: newassigned

comment:4 by Sasha Gaevsky, 8 years ago

comment:5 by Tim Graham, 8 years ago

Triage Stage: AcceptedReady for checkin

comment:6 by Tim Graham <timograham@…>, 8 years ago

Resolution: fixed
Status: assignedclosed

In 956cde8:

Fixed #26104 -- Fixed TypeError when passing number to forms.DurationField.

comment:7 by Tim Graham <timograham@…>, 8 years ago

In 6b258be:

Refs #26104 -- Replaced unnecessary force_str() with force_text().

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