Required field in Django model not mandatory?

大城市里の小女人 提交于 2020-08-07 06:17:39

问题


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

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': ''}

What am I missing?


回答1:


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

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.



来源:https://stackoverflow.com/questions/44101172/required-field-in-django-model-not-mandatory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!