physicalattraction
physicalattraction

Reputation: 6858

Required field in Django model not mandatory?

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?

Upvotes: 5

Views: 3514

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599450

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.

Upvotes: 8

Related Questions