0

The below model has a regex validator, however, when creating new objects (with standard model instantiation and model.objects.create() ), there is no error message given when creating an object that violates the validator. It allows the object to be saved.

Below is the code for the model:

class Area(models.Model):
    area = models.CharField(max_length=6, validators=[RegexValidator(
        regex='^[A-Z]{1,2}[0-9][A-Z0-9]?$',
        message='Area is not in correct format',
        code='invalid_area'
    )])

Any advise would be much appreciated.

Saif
  • 422
  • 5
  • 19

1 Answers1

1

Model data is validated by the DjangoForm before it's inserted into a model instance. But there is no validation checks in model.save method. So you can trigger validation for you model like this


class YourModel(models.Model):
    ...

    def save(self, *args, **kwargs):
        self.full_clean()
        super(YourModel, self).save(*args, **kwargs)

Here more detailed answer to your question Is this the way to validate Django model fields?

Yevhen Bondar
  • 4,357
  • 1
  • 11
  • 31