Opened 5 years ago

Closed 5 years ago

#31041 closed Bug (invalid)

Custom validation in the clean method triggers before checking the fields exist or not.

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

Description

I have the following code in my models file in Django:


class MyModel(models.Model):
        ...
    foo = models.IntegerField()
    bar = models.IntegerField()
    
    def validate_foo_bar(self):
        self._validation_errors = {}
        if self.foo > self.bar:
            self._validation_errors['foo'] = ['Must be greater than bar.']
            self._validation_errors['bar'] = ['Must be less than foo.']
            
    def clean(self):
        self.validate_foo_bar()
        if bool(self._validation_errors):
    		raise ValidationError(self._validation_errors)
    	super(MyModel, self).clean()

Hopefully the idea is clear. I check for errors in the clean method and raise them if they occur. When I use an admin form to create an object, if I leave the foo and bar fields empty, I get the following error:

if self.foo > self.bar:
TypeError: '>' not supported between instances of 'NoneType' and 'NoneType'

Why is this happening? Shouldn't the requirement check trigger before the method I wrote? Thanks for any help.

Change History (1)

comment:1 by Mariusz Felisiak, 5 years ago

Component: UncategorizedDatabase layer (models, ORM)
Resolution: invalid
Status: newclosed
Summary: Custom validation in the clean method triggers before checking the fields exist or notCustom validation in the clean method triggers before checking the fields exist or not.
Type: UncategorizedBug

Please don't use Trac as a support channel. If you accept None values you need to handle them in comparisons, see also documentation.

Closing per TicketClosingReasons/UseSupportChannels.

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