Ron
Ron

Reputation: 23466

BooleanField custom validator not working

I wrote a custom validator for a BooleanField to ensure saving an object with a true value. I took the idea from this post.

Here's my model:

terms_accepted = models.BooleanField(u"Terms accepted", validators=[validate_boolean])

Here's the custom validator:

def validate_boolean(value):
if not value:
    raise ValidationError(u"Durp!")

But the validator is never executed. I put a debug breakpoint there but nothing happens.

I used non-custom validators before (on IntegerFields) and they work like a charm, for example:

validators=[MinValueValidator(1900), MaxValueValidator(2014)]

Any ideas what I might be doing wrong? Or is it maybe a django bug?

Upvotes: 1

Views: 429

Answers (1)

ruddra
ruddra

Reputation: 51978

According to This Docs for validating objects:

You can clean_fields(exclude=None) which will validate all fields in model except the fields in exclude.

From This doc:

Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form.

More information about validating here.

EDIT

For field specific errors, clean_<field>() can be used in forms. Example:

terms_accepted= forms.BooleanField()
-------
-------
def clean_terms_accepted(self):
    data = self.cleaned_data
    if data['terms_accepted'] is not None:
        return True
    else:
        msg="Durp!"
        self._errors["terms_accepted"] = self.error_class([msg])
        return False

Upvotes: 2

Related Questions