Opened 2 years ago

Closed 2 years ago

#27476 closed Bug (invalid)

model Integer fields (and derivatives) do not raise a ValidationError while other types do

Reported by: Romeo Mihalcea Owned by: nobody
Component: Database layer (models, ORM) Version: 1.10
Severity: Normal Keywords: models, integer, ValidationError
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Romeo Mihalcea)

I have a model with Decimal fields, Boolean fields and some Integer fields. While testing with invalid data (I mostly supplied a string to these fields) I noticed that the integer fields do not raise a ValidationError while all of the other fields do so. Supplying a string to all Integer fields raise a ValueError instead which looks like all other fields have a basic validation in place while the Integers do not. I know I'm supposed to perform the validations before the data reaches the model but this is testing and I like to make sure everything is as intended.

Example:

# model
class Worker(models.Model):
    ...
    disabled = models.BooleanField(default=False)
    max_execution = models.PositiveSmallIntegerField(default=3600, null=False)


# testcase
class TestModelWorker(unittest.TestCase):

    def test_max_execution(self):
        # Here we expect a Python ValueError to be raised when providing a string
        # as an argument to what is a `PositiveSmallIntegerField` 
        with self.assertRaises(ValueError) as e:
            Worker.create(
                name="Worker",
                max_execution='s'
            )

        self.assertIn('invalid literal for int() with base 10', str(e.exception))

    def test_disabled(self):
        # While here we can expect a `ValidationError` when providing a string to a `BooleanField`
        with self.assertRaises(ValidationError) as e:
            Worker.create(
                name="Worker",
                disabled='s'
            )
        self.assertIn('value must be either True or False', str(e.exception))

Change History (6)

comment:1 Changed 2 years ago by Tim Graham

Can you please provide some sample code that demonstrates the issue?

comment:2 Changed 2 years ago by Romeo Mihalcea

Description: modified (diff)

comment:3 in reply to:  2 Changed 2 years ago by Romeo Mihalcea

Replying to Romeo Mihalcea:
Added some modifications

comment:4 Changed 2 years ago by Romeo Mihalcea

Description: modified (diff)

comment:5 Changed 2 years ago by Tim Graham

I'm not certain whether or not this should be a bug. The inconsistency is unexpected I suppose, but from a public API standpoint, my understanding is that validation isn't expected on a model until calling Model.full_clean(), If you'd like to propose a patch, that might help evaluate the idea.

comment:6 Changed 2 years ago by Tim Graham

Resolution: invalid
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top