Identify the changed fields in django post_save signal

If you want to compare state before and after save action, you can use pre_save signal which provide you instance as it should become after database update and in pre_save you can read current state of instance in database and perform some actions based on difference. from django.db.models.signals import pre_save from django.dispatch import receiver @receiver(pre_save, … Read more

The right place to keep my signals.py file in a Django project

If you’re using Django<=1.6 I’d recommend Kamagatos solution: just import your signals at the end of your models module. For future versions of Django (>=1.7), the recommended way is to import your signals module in your app’s config ready() function: my_app/apps.py from django.apps import AppConfig class MyAppConfig(AppConfig): name=”my_app” def ready(self): import my_app.signals my_app/__init__.py default_app_config = … Read more

Django post_save() signal implementation

If you really want to use signals to achieve this, here’s briefly how, from django.db.models.signals import post_save from django.dispatch import receiver class TransactionDetail(models.Model): product = models.ForeignKey(Product) # method for updating @receiver(post_save, sender=TransactionDetail, dispatch_uid=”update_stock_count”) def update_stock(sender, instance, **kwargs): instance.product.stock -= instance.amount instance.product.save()

TransactionManagementError “You can’t execute queries until the end of the ‘atomic’ block” while using signals, but only during Unit Testing

I ran into this same problem myself. This is caused by a quirk in how transactions are handled in the newer versions of Django coupled with a unittest that intentionally triggers an exception. I had a unittest that checked to make sure a unique column constraint was enforced by purposefully triggering an IntegrityError exception: def … Read more