2012-08-03 87 views
10

我有以下型號:Django的模型驗證工作不

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) 

在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() 
+0

它應該給完整性錯誤。您的模型/數據庫同步正確嗎?您的應用程序的sqlall將有所幫助。 – Rohan 2012-08-03 04:59:51

+0

是的,我已經做到了......沒有改善 – 2012-08-03 05:02:13

回答

23

的文檔explicit about this

注意驗證器,當你保存模型將不會自動運行,但如果您使用的是的ModelForm,它會在您的表單中包含的任何字段上運行您的驗證器。

如果您沒有使用表單,則在保存之前調用clean方法是您的責任。

調用模型驗證可以強制這樣的:

model_instance.full_clean()