Fahmi Eshaq
Fahmi Eshaq

Reputation: 378

Set Model Field as Required in Django

Django doesn't enforce NOT NULL at the model/database level. device_serial is neither supposed to have blank '' nor null

class Device(models.Model):
       device_serial = models.CharField(max_length=36, unique=True, null=False, blank=False)
       ....etc

The statement below works totally fine! I expect it to fail because device_serial is required. It shouldn't accept empty string ''

Device.objects.create(device_serial='')

How can I make a field required at the model / database level? What could I possibly be doing wrong here? I don't see where did I go wrong. I tried ''.strp() to convert empty string to None but it didn't work

Upvotes: 2

Views: 1789

Answers (3)

DekaS
DekaS

Reputation: 21

In my case was enough by setting default=None in field definition.

In your case:

class Device(models.Model):
       device_serial = models.CharField(max_length=36, unique=True, default=None)

I've removed null=False and blank=False due it's the default value.

Upvotes: 0

Fahmi Eshaq
Fahmi Eshaq

Reputation: 378

Mohd's answer worked! Alternatively, a check constraint at the DB level worked as well.

class Meta:
    constraints = [
        models.CheckConstraint(check=~models.Q(device_serial=''), name='chk_device_device_serial')
    ]

Upvotes: 2

Mohd
Mohd

Reputation: 5613

As far as the database is concerned, it only allows null/not null which is handled by null=True/False and defaults to False. The blank=True/False is for admin page only.

The string '' is not considered null which is why it is accepted by the database when you have null=False constraint.

If you want to to avoid blank strings in database level you can override save() on the model itself and raise an exception when device_serial is set to an empty string, for example:

from django.core.exceptions import ValidationError

class Device(models.Model):
    device_serial = models.CharField(max_length=36, unique=True)

    def save(self, *args, **kwargs):
        if self.device_serial == '':
            raise ValidationError('device_serial cannot be empty')
        super().save(*args, **kwargs)

Now when you try to create an object with empty string (which calls save()), the following exception will be raised:

django.core.exceptions.ValidationError: ['device_serial cannot be empty']

Upvotes: 4

Related Questions