5

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?

physicalattraction
  • 6,485
  • 10
  • 63
  • 122

1 Answers1

8

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.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • [See here](https://docs.djangoproject.com/en/1.11/ref/models/instances/#validating-objects) for more info on validating models. To validate the entirety of the model use `.full_clean()`. – Jessie May 21 '17 at 22:00
  • 2
    Mmm, that is clear! I thought that this would be set on the database level, but that is then an incorrect assumption. Thanks! – physicalattraction May 22 '17 at 14:39