0

I wonder if Django offers this feature some other web frameworks like Ruby on Rails do. I am talking about means to forbid certain states where the values of the attributes being saved, for example:

model.active = False
model.authorized = True
model.save() # this should fail

We can have a model where both active and authorized are either both True or False, but we cannot have any other combination. Sorry but I can't think of a better example right now, I hope the intent is understood.

So, does Django have any means for handling these situations? Or implementing it ourselves when the method save is called is the only way?

dabadaba
  • 9,064
  • 21
  • 85
  • 155

1 Answers1

0

You can override the save method on your model.

class TestModel(models.Model):
    def save(self, *args, **kwargs):
        if self.active == False and self.authorized == True:
            raise ValidationError("Some descriptive text here")
        else:
            return super(TestModel, self).save(*args, **kwargs)

That's the simplest method to do this, but not the best.

You can also do model validation overriding the clean method, but then full_clean must be called explicitly before calling save if not using this through a ModelForm

The third method applies only if you're using a form to accept the changes, in which case you can override clean as above, but the model's full_clean is the form's clean methods are called when the form's is_valid method is called.

Andee
  • 753
  • 3
  • 12
  • 1
    Not all views would be able to [handle the validation errors](http://stackoverflow.com/a/8771090/1324033). Clean methods would be the correct way to go though – Sayse Dec 09 '16 at 09:48