The default for Django models is blank=False
, which applies to form validation, and null=False
, which means that the database cannot contain NULL
. Neither of these will prevent an empty string from saving in your database if you do not use a form to instantiate the model instance.
A good way to do this without using a form (e.g., if you are trying to instantiate the class using create
or get_or_create
) is to override the model's clean
method and call full_clean
in the save
method:
from django.core.exceptions import ValidationError
def clean(self):
if self.title == "":
raise ValidationError("Database should not contain an empty string title!")
def save(self):
self.full_clean()
super(YourModel, self).save(*args, **kwargs)
In your case you could probably put your validation into the save
function as well. The advantage of overriding the clean
method and calling full_clean
in the save method is that the ValidationError
will be added to a form's non_field_errors
.