django模型验证不起作用

Viv*_*k S 10 django django-models

我有以下型号:

class CardInfo(models.Model):
    custid = models.CharField(max_length=30, db_index=True, primary_key = True)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    street = models.CharField(max_length=100)
    building = models.CharField(max_length=100)
    city = models.CharField(max_length=100)
    state = models.CharField(max_length=100)
    zipcode = models.CharField(max_length=100)
    payment_method = models.CharField(max_length=100, null=True, blank=True)
    amount = models.CharField(default = '0',max_length=10, null=True, blank=True)
    valid_to_month = models.CharField(max_length=100, null=True, blank=True)
    valid_to_year = models.CharField(max_length=100, null=True, blank=True)
def __unicode__(self):
    return "Cust ID %s" %(self.custid)
Run Code Online (Sandbox Code Playgroud)

在shell中,当我给full_clean我得到验证错误但是在保存它得到保存而不是抛出错误.为什么会这样?我正在使用django1.3和python 2.6:

c=CardInfo(custid="Asasasas")
c.full_clean()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/python2.6/lib/python2.6/site-packages/django/db/models/base.py", line 828, in full_clean
raise ValidationError(errors)
ValidationError: {'building': [u'This field cannot be blank.'], 'city': [u'This field cannot be blank.'], 'first_name': [u'This field cannot be blank.'], 'last_name': [u'This field cannot be blank.'], 'zipcode': [u'This field cannot be blank.'], 'state': [u'This field cannot be blank.'], 'street': [u'This field cannot be blank.']}
c.save()
Run Code Online (Sandbox Code Playgroud)

Dan*_*man 23

文档明确说明了这一点:

请注意,保存模型时不会自动运行验证程序,但如果您使用的是ModelForm,它将在表单中包含的任何字段上运行验证程序.

如果您没有使用表单,则在保存之前调用干净方法是您的责任.

调用模型验证器可以像这样强制:

model_instance.full_clean()
Run Code Online (Sandbox Code Playgroud)