szaman
szaman

Reputation: 6756

Custom model validator does not work on edit

I wrote a validator for my model which is:

def validate_is_default(value):
    if Wizard.objects.filter(set_as_default=True).count() == 1:
        if value is True:
            raise ValidationError(_('You can mark only one configuration as default'))
        else:
            raise ValidationError(_('You have to mark one configuration as default'))

And I have model when I use it:

class MyModel(models.Model):
    name = models.CharField(_('Wizard name'), default='Default', max_length=32, blank=False)
    ...
    set_as_default = models.BooleanField(_('Set as default setup'), default=False, validators=[validate_is_default])

In validator I wanted to check if there is only one record in database that has set_as_default=True. This works fine when I add new record, but fails when I try to edit one. How to solve this?

I use this in admin panel. I would not like to change default form, but solve it somehow using this validators. Is it possible?

Upvotes: 0

Views: 177

Answers (1)

Luke Sneeringer
Luke Sneeringer

Reputation: 9428

Depending on your database backend, columns using models.BooleanField won't always be given the Python values True and False by Django (in particular, if you're using MySQL, you'll get back 1 or 0 because MySQL has no boolean type and Django simply uses a tinyint).

Therefore, instead of the clause if value is True:, write just if value:. Like so:

def validate_is_default(value):
    if Wizard.objects.filter(set_as_default=True).count() == 1:
        if value:
            raise ValidationError(_('You can mark only one configuration as default'))
        else:
            raise ValidationError(_('You have to mark one configuration as default'))

You haven't provided enough information for me to conclusively state that this is your problem, but it's likely that it is.

Upvotes: 2

Related Questions