4

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 :)

Apostolos
  • 7,763
  • 17
  • 80
  • 150

2 Answers2

3

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!')
daveoncode
  • 18,900
  • 15
  • 104
  • 159
1

You would generally want to divide this to two problems:

Udi
  • 29,222
  • 9
  • 96
  • 129
  • Is the TransactionManagementError the right exception for this job?I would like if django docs shared some real life case studies... – Apostolos Nov 13 '13 at 10:36