Django模型中的必填字段不是必填项? [英] Required field in Django model not mandatory?

查看:81
本文介绍了Django模型中的必填字段不是必填项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Django模型:

I have the following Django model:

class Customer(models.Model):
    email = models.EmailField(unique=True)

在我的测试用例中,我没有电子邮件就实例化了它.

In my testcase, I instantiate it without an e-mail.

class CustomerTestCase(TestCase):
    def test_that_customer_can_be_created_with_minimum_data(self):
        customer = Customer.objects.create()
        print(customer.__dict__)

我希望它会引发错误,但是它会创建一个带有空字段 email 的记录.如果我明确地说 null = False blank = False ,也会发生同样的事情.相反,它只会打印空的电子邮件.

I expect it to raise an error, but it creates a record with an empty field email. The same thing happens if I explicitly say null=False and blank=False. Instead, it just prints the empty email.

{'email': ''}

我想念什么?

推荐答案

您遗漏了验证未在保存时运行的事实-请参见

You're missing the fact that validation is not run on save - see the validation docs:

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

Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form.

正如该文档所暗示的那样,通常在表单的上下文中进行验证.

As that doc implies, usually validation is carried out in the context of a form.

这篇关于Django模型中的必填字段不是必填项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆