Sapan Bhatia | 0235e98 | 2014-09-03 13:14:40 -0400 | [diff] [blame] | 1 | from django.db.models.signals import post_save |
| 2 | from django.dispatch import receiver |
| 3 | import pdb |
Sapan Bhatia | 3a5980e | 2014-09-15 03:48:11 -0400 | [diff] [blame] | 4 | from core.models import * |
Sapan Bhatia | 475c597 | 2014-11-05 10:32:41 -0500 | [diff] [blame] | 5 | from dependency_walker import * |
Sapan Bhatia | 3a5980e | 2014-09-15 03:48:11 -0400 | [diff] [blame] | 6 | import model_policies |
Sapan Bhatia | 0235e98 | 2014-09-03 13:14:40 -0400 | [diff] [blame] | 7 | |
Scott Baker | 79eaac2 | 2014-10-21 15:05:29 -0700 | [diff] [blame] | 8 | modelPolicyEnabled = True |
| 9 | |
| 10 | def EnableModelPolicy(x): |
| 11 | global modelPolicyEnabled |
| 12 | modelPolicyEnabled = x |
| 13 | |
Sapan Bhatia | 475c597 | 2014-11-05 10:32:41 -0500 | [diff] [blame] | 14 | def update_dep(d, o): |
| 15 | if (d.updated < o.updated): |
| 16 | d.save(update_fields=['updated']) |
| 17 | |
| 18 | def delete_if_inactive(d, o): |
| 19 | #print "Deleting %s (%s)"%(d,d.__class__.__name__) |
| 20 | d.delete() |
| 21 | return |
| 22 | |
Sapan Bhatia | 0235e98 | 2014-09-03 13:14:40 -0400 | [diff] [blame] | 23 | @receiver(post_save) |
Scott Baker | d56ccd7 | 2014-09-30 14:53:45 -0700 | [diff] [blame] | 24 | def post_save_handler(sender, instance, **kwargs): |
Scott Baker | 79eaac2 | 2014-10-21 15:05:29 -0700 | [diff] [blame] | 25 | if not modelPolicyEnabled: |
| 26 | return |
Sapan Bhatia | 475c597 | 2014-11-05 10:32:41 -0500 | [diff] [blame] | 27 | |
| 28 | sender_name = sender.__name__ |
| 29 | policy_name = 'model_policy_%s'%sender_name |
Sapan Bhatia | 640f2b7 | 2014-09-15 04:04:32 -0400 | [diff] [blame] | 30 | |
| 31 | if (not kwargs['update_fields']): |
Sapan Bhatia | 475c597 | 2014-11-05 10:32:41 -0500 | [diff] [blame] | 32 | # Automatic dirtying |
| 33 | walk_inv_deps(update_dep, instance) |
| 34 | |
Sapan Bhatia | 640f2b7 | 2014-09-15 04:04:32 -0400 | [diff] [blame] | 35 | try: |
Scott Baker | c1f9cce | 2014-10-09 12:03:22 -0700 | [diff] [blame] | 36 | policy_handler = getattr(model_policies, policy_name, None) |
| 37 | if policy_handler is not None: |
| 38 | policy_handler.handle(instance) |
Sapan Bhatia | 640f2b7 | 2014-09-15 04:04:32 -0400 | [diff] [blame] | 39 | except: |
| 40 | pass |
Sapan Bhatia | 475c597 | 2014-11-05 10:32:41 -0500 | [diff] [blame] | 41 | elif 'deleted' in kwargs['update_fields']: |
| 42 | walk_inv_deps(delete_if_inactive, instance) |
| 43 | |