[Answered ]-Django model validation not raising Exception on full_clean()

1๐Ÿ‘

โœ…

A validator should raise a ValidationError in case the condition is not met, not return True or False, so:

from django.core.exceptions import ValidationError

def home_away_valid(value):
    if value not in ('H', 'A'):
        raise ValidationError('Must be home or away')

You also might want to use 'H' and 'A' as choices, this will render the form with a ChoiceField, making it less likely to make mistakes:

class Team(models.Model):
    HOME_AWAY = (
        ('H', 'Home'),
        ('A', 'Away')
    )

    name = models.CharField(max_length=180)
    home = models.CharField(max_length=2, choices=HOME_AWAY, validators=[home_away_valid], default='H', db_index=True)

Leave a comment