How can you create a non-empty CharField in Django?

Viewed 17526

I have a simple model which looks like this:

class Group(models.Model):
    name = models.CharField(max_length = 100, blank=False)

I would expect this to throw an integrity error, but it does not:

group = Group() # name is an empty string here
group.save()

How can I make sure that the name variable is set to something non-empty? I.e to make the database reject any attempts to save an empty string?

5 Answers

another option that doesn't require you to manually call clean is to use this:

name = models.CharField(max_length=100, blank=False, default=None)
  • blank will prevent an empty string to be provided in the admin or using a form or serializer (most cases). However as pointed out in the comments, this unfortunately does not prevent things like model.name = "" (manually setting blank string)
  • default=None will set name to None when using something like group = Group(), thus raising an exception when calling save

I spent a long time looking for the best solution for this simple (and old) problem, And as of Django 2.2, there is actually a really simple answer, so I'll write it here in case someone still encounters the same problem:

Since Django 2.2, we can define CheckConstraints, so it's easy to define a non-empty string constraint:

from django.db import models

class Article(models.Model):
   title = models.CharField(max_length=32)

    class Meta:
        constraints = [
            models.CheckConstraint(check=~models.Q(title=""), name="non_empty_title")
        ]
Related