【问题标题】:django model validation not workingdjango模型验证不起作用
【发布时间】:2012-08-03 04:43:48
【问题描述】:

我有以下型号:

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()

【问题讨论】:

  • 它应该给出完整性错误。您的模型/数据库是否正确同步? sqlall 您的应用程序将有所帮助。
  • 是的,我做到了...没有改善

标签: django django-models


【解决方案1】:

文档是explicit about this:

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

如果您不使用表单,则在保存之前调用 clean 方法是您的责任。

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

model_instance.full_clean()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多