blob: 38cc4dfed53e9411e71c0dd5237d2a0c261a2a3f [file] [log] [blame]
Sapan Bhatia0235e982014-09-03 13:14:40 -04001from django.db.models.signals import post_save
2from django.dispatch import receiver
3import pdb
Sapan Bhatia3a5980e2014-09-15 03:48:11 -04004from core.models import *
Sapan Bhatia475c5972014-11-05 10:32:41 -05005from dependency_walker import *
Sapan Bhatia3a5980e2014-09-15 03:48:11 -04006import model_policies
Sapan Bhatia0235e982014-09-03 13:14:40 -04007
Scott Baker79eaac22014-10-21 15:05:29 -07008modelPolicyEnabled = True
9
10def EnableModelPolicy(x):
11 global modelPolicyEnabled
12 modelPolicyEnabled = x
13
Sapan Bhatia475c5972014-11-05 10:32:41 -050014def update_dep(d, o):
15 if (d.updated < o.updated):
16 d.save(update_fields=['updated'])
17
18def delete_if_inactive(d, o):
19 #print "Deleting %s (%s)"%(d,d.__class__.__name__)
20 d.delete()
21 return
22
Sapan Bhatia0235e982014-09-03 13:14:40 -040023@receiver(post_save)
Scott Bakerd56ccd72014-09-30 14:53:45 -070024def post_save_handler(sender, instance, **kwargs):
Scott Baker79eaac22014-10-21 15:05:29 -070025 if not modelPolicyEnabled:
26 return
Sapan Bhatia475c5972014-11-05 10:32:41 -050027
28 sender_name = sender.__name__
29 policy_name = 'model_policy_%s'%sender_name
Sapan Bhatia640f2b72014-09-15 04:04:32 -040030
31 if (not kwargs['update_fields']):
Sapan Bhatia475c5972014-11-05 10:32:41 -050032 # Automatic dirtying
33 walk_inv_deps(update_dep, instance)
34
Sapan Bhatia640f2b72014-09-15 04:04:32 -040035 try:
Scott Bakerc1f9cce2014-10-09 12:03:22 -070036 policy_handler = getattr(model_policies, policy_name, None)
37 if policy_handler is not None:
38 policy_handler.handle(instance)
Sapan Bhatia640f2b72014-09-15 04:04:32 -040039 except:
40 pass
Sapan Bhatia475c5972014-11-05 10:32:41 -050041 elif 'deleted' in kwargs['update_fields']:
42 walk_inv_deps(delete_if_inactive, instance)
43