Search code examples
pythondjangovalidation

Django Validators not working in shell command


Django Validators not working in shell command, it works just on Django Forms and Django Admin but not in shell commands. I have this:

Validator

def validate_cuit(value):
    """ Must be exactly 11 numeric characters """
    if len(value) != 11:
        raise CuitValidationException('CUIT should have 11 characters')

    if not value.isdigit():
        raise CuitValidationException('CUIT should only contain numeric characters')

    return value

Exception

class CuitValidationException(ValidationError):
    pass

Model

class Empresa(models.Model):
    name = models.CharField(max_length=120, validators=[validate_name])
    cuit = models.CharField(max_length=11, validators=[validate_cuit])

If I do this, I get no error

e = Empresa.objects.create(name="Testing Case", cuit='1')

The only way I found to solve this is by working on the save method:

def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        self.name = validate_name(self.name)
        self.cuit = validate_cuit(self.cuit)
        return super().save(force_insert, force_update, using, update_fields)

But I'm sure it shouldn't be neccesary, can you help me with this?


Solution

  • But I'm sure it shouldn't be neccesary, can you help me with this?

    Django does not run the validators when saving the item, only the ModelForms do, likely for performance reasons.

    Indeed, you can run the validators explicitly with the .full_clean() method [Django-doc]:

    e = Empresa(name="Testing Case", cuit='1')
    e.full_clean()  # will raise error
    e.save()