Reputation: 8101
When saving a django model using it's save method is there any way to make sure nothing happened during save and send a message to the user? I was thinking of the message framework and try except block?
try:
model.save()
add success message to message framework
except DatabaseError:
add error message to message framework
except TransactionManagementError:
add error message
Is this the right way to do that?Also which exception is more likely to be raised when trying to save a new instance of a model?I fairly new to django so be kind :)
Upvotes: 4
Views: 5541
Reputation: 19578
My approach is to use a base abstract model that all my models extend and in which I override the save method in order to catch exceptions and rollback transactions:
class AbstractModel(models.Model):
class Meta:
abstract = True
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
try:
super(AbstractModel, self).save(force_insert, force_update, using, update_fields)
except IntegrityError as saveException:
logger.exception('Rolling back transaction due to an error while saving %s...' % self.__class__.__name__)
try:
transaction.rollback()
except Exception as rollbackException:
logger.exception('Unable to rollback!')
Upvotes: 3
Reputation: 30472
You would generally want to divide this to two problems:
IntegrityError
. See: https://docs.djangoproject.com/en/dev/ref/exceptions/#database-exceptions (Django 1.6+ has some more errors). You should probably catch those and use something like messages.error
to notify the user.Upvotes: 1