How to make django textfield required

I'm somehow unable to make the field required, setting null and blank to True has no effect.

# models.py
from django.db import models

class ExampleModel(models.Model):
    text_field = models.TextField()

# tests.py
from django.test import TestCase
from .models import ExampleModel

class ExampleModelTestCase(TestCase):
    def test_text_field_integrity(self):
        with self.assertRaises(Exception):
            example = ExampleModel.objects.create()


Does example.full_clean() work?

cf. reference: http://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#django.db.models.Model.full_clean

You can explicitly set blank to False, although this is unnecessary since its default value is already False, as stated in the documentation.

As Sebastien already mentioned you need to use Model.full_clean in your test in order to achieve the desired effect. Here is how to do it:

models.py:

from django.db import models

class ExampleModel(models.Model):
    text_field = models.TextField(blank=False)

tests.py:

from django.test import TestCase
from .models import ExampleModel
from django.core.exceptions import ValidationError

class ExampleModelTestCase(TestCase):
    def test_text_field_integrity(self):
        example = ExampleModel.objects.create()
        with self.assertRaises(ValidationError):
            example.full_clean()

In the tests.py, I explicitly invoked the full_clean() method, which was the missing component in your implementation. Additionally, I opted to use ValidationError rather than the more general Exception, as the latter is too broad for this context. Nevertheless, the code would function correctly with Exception as well, given that ValidationError is a subclass of Exception.

Вернуться на верх