How to trigger clean method from model when updating?

1.7k views Asked by At

When I save my form I perform validation of data that is defined in my model

    def clean(self):
    model = self.__class__
    if self.unit and (self.is_active == True)  and model.objects.filter(unit=self.unit, is_terminated = False , is_active = True).exclude(id=self.id).count() > 0:
        raise ValidationError('Unit has active lease already, Terminate existing one prior to creation of new one or create a not active lease '.format(self.unit))

How can I trigger same clean method during simple update without a need to duplicate clean logic in my update view?(In my view I just perform update without any form)

Unit.objects.filter(pk=term.id).update(is_active=False)
1

There are 1 answers

0
Clément Denoix On BEST ANSWER

update don't call the save method of your model and so it's not possible for django to raise ValidationError exceptions in this case.

You need to at least call the full_clean method of your model before doing the update.

Maybe like this ?

unit = Unit.objects.get(pk=term.id)
unit.is_active = False    

try:
    unit.full_clean()
except ValidationError as e:
    # Handle the exceptions here

unit.save()

Reference: https://docs.djangoproject.com/en/1.11/ref/models/instances/#validating-objects