[Django]-Don't allow empty string on model attribute

6👍

You could still use a form to validate the data and create the model object, as a ModelForm returns the object it creates. I’ve used that methodology when doing batch updates to models from .xls files and it worked out great.

Using a form in this way also gives you the chance to log an error for what went wrong, kick off other processes, or whatever you’d like.

It also alleviates you from having to edit the database by hand, and the form could also plug in a default value if the string is empty.

Hope that helps you out.

5👍

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.

1👍

MySQL has limited support for constraints, so you’ll have to either use Triggers (see here for more about how to use triggers) or adjust your parser.

Assuming you’re OK with not having NULL as a field value either, you could set your model field to null=False (null is purely database-related, whereas blank is validation-related) and adjust your parser to set any variables that are empty strings to None:

if not variable:
    variable = None

This previous SO question might also be helpful:
I'm looking for a constraint to prevent the insert of an empty string in MySQL

Leave a comment