Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't allow empty string on model attribute

Tags:

django

So I have a book model with the following attribute:

title = models.CharField(max_length=250)

In admin or model forms this won't allow empty string to be saved because blank=False by default. But in my case I am parsing xml and creating the models that way so I am not using any forms at all.

So I was wondering is there a constraint I can set that doesn't allow empty strings or do I have to write my model field or adjust my parser?

like image 275
Pickels Avatar asked Feb 05 '26 06:02

Pickels


2 Answers

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.

like image 102
Brandon Avatar answered Feb 06 '26 21:02

Brandon


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.

like image 33
YPCrumble Avatar answered Feb 06 '26 19:02

YPCrumble



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!