#24229: forms.IntegerField.clean() fails to clean float objects that are 
integers
-----------------------------+--------------------
     Reporter:  jdufresne    |      Owner:  nobody
         Type:  New feature  |     Status:  new
    Component:  Forms        |    Version:  master
     Severity:  Normal       |   Keywords:
 Triage Stage:  Unreviewed   |  Has patch:  0
Easy pickings:  0            |      UI/UX:  0
-----------------------------+--------------------
 Django forms are useful for validating user input beyond just HTML forms.
 They can be used to validate and clean user input from multiple sources.

 One source could potentially be an spreadsheets. Imagine a spreadsheet
 where each row is data keyed by its header. Each row is validated by a
 Django `Form` object, if the form is valid,  some action occurs.

 One issue, MS Excel represents all numbers in cells as floats, even
 integers. So for this to work, a float with value `1.0` should be cleaned
 by `forms.IntegerField` as `1`. Currently this fails as
 `forms.IntegerField.to_python()` is implemeted as:

 {{{
 try:
     value = int(str(value))
 except (ValueError, TypeError):
     raise ValidationError(self.error_messages['invalid'], code='invalid')
 }}}

 But this fails for floats:

 {{{
 $ python -c 'int(str(1.0))'
 Traceback (most recent call last):
   File "<string>", line 1, in <module>
 ValueError: invalid literal for int() with base 10: '1.0'
 }}}

 The following test demonstrates that this does not work in Django:

 {{{
 $ git diff
 diff --git a/tests/forms_tests/tests/test_fields.py
 b/tests/forms_tests/tests/test_fields.py
 index fda4512..3069520 100644
 --- a/tests/forms_tests/tests/test_fields.py
 +++ b/tests/forms_tests/tests/test_fields.py
 @@ -184,6 +184,7 @@ class FieldsTests(SimpleTestCase):
          self.assertRaisesMessage(ValidationError, "'Enter a whole
 number.'", f.clean, '1a')
          self.assertEqual(f.max_value, None)
          self.assertEqual(f.min_value, None)
 +        self.assertEqual(1, f.clean(1.0))

      def test_integerfield_2(self):
          f = IntegerField(required=False)
 }}}

 I propose that the `fields.IntegerField` be able to clean float objects
 that represent an integer. This will help make Django forms useful for
 user input beyond simple HTML forms.

--
Ticket URL: <https://code.djangoproject.com/ticket/24229>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/052.0639150415df65a26ab96b8d4396db66%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to