简体   繁体   English

Django model 验证未在 full_clean() 上引发异常

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

I have a Model and ModelForm with custom validator (which only allows "H" or "A" in the CharField):我有一个Model和带有自定义验证器的ModelForm (在 CharField 中只允许“H”或“A”):

def home_away_valid(value):
    return value == 'H' or value == 'A'


class Team(models.Model):
    name = models.CharField(max_length=180)
    home = models.CharField(max_length=2, validators=[home_away_valid], default='H', db_index=True)


class TeamForm(ModelForm):
    class Meta:
        model = Team
        fields = ['home', 'name']

However when I run full_clean() with another value (not H or A) it doesn't not raise a validation exception:但是,当我使用另一个值(不是 H 或 A)运行 full_clean() 时,它不会引发验证异常:

try:
    team = TeamForm({
        'name': 'Test Team',
        'home': 'S'
    })
    team.full_clean()
    new_team = team.save()
    print(new_team.id)
except ValidationError as e:
    print(e)

Why does this not raise an Exception?为什么这不会引发异常? (I have tried doing the full_clean() on both the ModelForm and Model , neither raises an Exception) (我已经尝试在ModelFormModel上执行full_clean() ,但都没有引发异常)

A validator should raise a ValidationError in case the condition is not met, not return True or False , so:验证器应该在不满足条件的情况下引发ValidationError ,而不是返回TrueFalse ,因此:

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:您可能还想使用'H''A'作为选择,这将使用ChoiceField呈现表单,从而减少出错的可能性:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM