I'm trying to do a simple error reporting system within my Django classes, but I cannot get to save a new object (from another class) if I raise a ValidationError.
Here is an example of what I want to do:
from django.db import models
from django.core.exceptions import ValidationError
class History(models.Model):
data = models.CharField(max_length=255)
timestamp = models.DateTimeField(auto_now_add=True)
class PositiveNumber(models.Model):
number = models.IntegerField()
def save(self, *args, **kwargs):
if self.number < 0:
h = History(data="Error writing %d into 'Positive Numbers'" % (self.number,))
h.save() # Here is the problem: h doesn't get saved
raise ValidationError('Positive numbers only')
else:
h = History(data="Saved %d into 'Positive Numbers'" % (self.number,))
h.save()
return super(PositiveNumber, self).save(*args, **kwargs)
The problem is that if I raise an exception, even if it is risen after I do the h.save(), h doesn't get saved.
This makes all the sense because Django is so intelligent that shouldn't let you commit to the database if there is an error, but I can't find anywhere in the documentation where I can override this to deal with this specific situation.
... or maybe I'm simply conceptually wrong and I have to deal with this elsewhere (I'm trying to do a robust system where others can write code for it so it should be fail-safe).