Added embeddable_content_types registry to track what content types are embeddable...
[philo.git] / contrib / penfield / embed.py
1 from django.contrib.contenttypes import generic
2 from django.contrib.contenttypes.models import ContentType
3 from django.core.exceptions import ValidationError
4 from django.db import models
5 from django.template import loader, loader_tags, Parser, Lexer, Template
6 import re
7 from philo.models.fields import TemplateField
8 from philo.contrib.penfield.templatetags.embed import EmbedNode
9 from philo.utils import nodelist_crawl, ContentTypeRegistryLimiter
10
11
12 embeddable_content_types = ContentTypeRegistryLimiter()
13
14
15 class Embed(models.Model):
16         embedder_content_type = models.ForeignKey(ContentType, related_name="embedder_related")
17         embedder_object_id = models.PositiveIntegerField()
18         embedder = generic.GenericForeignKey("embedder_content_type", "embedder_object_id")
19         
20         embedded_content_type = models.ForeignKey(ContentType, related_name="embedded_related")
21         embedded_object_id = models.PositiveIntegerField()
22         embedded = generic.GenericForeignKey("embedded_content_type", "embedded_object_id")
23         
24         def delete(self):
25                 # This needs to be called manually.
26                 super(Embed, self).delete()
27                 
28                 # Cycle through all the fields in the embedder and remove all references
29                 # to the embedded object.
30                 embedder = self.embedder
31                 for field in embedder._meta.fields:
32                         if isinstance(field, EmbedField):
33                                 attr = getattr(embedder, field.attname)
34                                 setattr(embedder, field.attname, self.embed_re.sub('', attr))
35                 
36                 embedder.save()
37         
38         def get_embed_re(self):
39                 """Convenience function to return a compiled regular expression to find embed tags that would create this instance."""
40                 if not hasattr(self, '_embed_re'):
41                         ct = self.embedded_content_type
42                         self._embed_re = re.compile("{%% ?embed %s.%s %s( .*?)? ?%%}" % (ct.app_label, ct.model, self.embedded_object_id))
43                 return self._embed_re
44         embed_re = property(get_embed_re)
45         
46         class Meta:
47                 app_label = 'penfield'
48
49
50 def sync_embedded_instances(model_instance, embedded_instances):
51         model_instance_ct = ContentType.objects.get_for_model(model_instance)
52         
53         # Cycle through all the embedded instances and make sure that they are linked to
54         # the model instance. Track their pks.
55         new_embed_pks = []
56         for embedded_instance in embedded_instances:
57                 embedded_instance_ct = ContentType.objects.get_for_model(embedded_instance)
58                 new_embed = Embed.objects.get_or_create(embedder_content_type=model_instance_ct, embedder_object_id=model_instance.id, embedded_content_type=embedded_instance_ct, embedded_object_id=embedded_instance.id)[0]
59                 new_embed_pks.append(new_embed.pk)
60         
61         # Then, delete all embed objects related to this model instance which do not relate
62         # to one of the newly embedded instances.
63         Embed.objects.filter(embedder_content_type=model_instance_ct, embedder_object_id=model_instance.id).exclude(pk__in=new_embed_pks).delete()
64
65
66 class EmbedField(TemplateField):
67         def process_node(self, node, results):
68                 if isinstance(node, EmbedNode) and node.instance is not None:
69                         if node.content_type.model_class() not in embeddable_content_types.classes:
70                                 raise ValidationError("Class %s.%s cannot be embedded." % (node.content_type.app_label, node.content_type.model))
71                         
72                         if not node.instance:
73                                 raise ValidationError("Instance with content type %s.%s and id %s does not exist." % (node.content_type.app_label, node.content_type.model, node.object_pk))
74                         
75                         results.append(node.instance)
76         
77         def clean(self, value, model_instance):
78                 value = super(EmbedField, self).clean(value, model_instance)
79                 
80                 if not hasattr(model_instance, '_embedded_instances'):
81                         model_instance._embedded_instances = set()
82                 
83                 model_instance._embedded_instances |= set(nodelist_crawl(Template(value).nodelist, self.process_node))
84                 
85                 return value
86
87
88 try:
89         from south.modelsinspector import add_introspection_rules
90 except ImportError:
91         pass
92 else:
93         add_introspection_rules([], ["^philo\.contrib\.penfield\.embed\.EmbedField"])
94
95
96 # Add a post-save signal function to run the syncer.
97 def post_save_embed_sync(sender, instance, **kwargs):
98         if hasattr(instance, '_embedded_instances') and instance._embedded_instances:
99                 sync_embedded_instances(instance, instance._embedded_instances)
100 models.signals.post_save.connect(post_save_embed_sync)
101
102
103 # Deletions can't cascade automatically without a GenericRelation - but there's no good way of
104 # knowing what models should have one. Anything can be embedded! Also, cascading would probably
105 # bypass the Embed model's delete method.
106 def post_delete_cascade(sender, instance, **kwargs):
107         if sender in embeddable_content_types.classes:
108                 # Don't bother looking for Embed objects that embed a contenttype that can't be embedded.
109                 ct = ContentType.objects.get_for_model(sender)
110                 embeds = Embed.objects.filter(embedded_content_type=ct, embedded_object_id=instance.id)
111                 for embed in embeds:
112                         embed.delete()
113         
114         if not hasattr(sender._meta, '_has_embed_fields'):
115                 sender._meta._has_embed_fields = False
116                 for field in sender._meta.fields:
117                         if isinstance(field, EmbedField):
118                                 sender._meta._has_embed_fields = True
119                                 break
120         
121         if sender._meta._has_embed_fields:
122                 # If it doesn't have embed fields, then it can't be an embedder.
123                 Embed.objects.filter(embedder_content_type=ct, embedder_object_id=instance.id).delete()
124 models.signals.post_delete.connect(post_delete_cascade)