2 from django.conf import settings
3 from django.contrib.contenttypes.models import ContentType
4 from django.contrib.contenttypes import generic
5 from django.core.exceptions import ValidationError
6 from django.db import models
7 from django.http import HttpResponse
8 from django.template import TemplateDoesNotExist, Context, RequestContext, Template as DjangoTemplate, add_to_builtins as register_templatetags, TextNode, VariableNode
9 from django.template.loader_tags import BlockNode, ExtendsNode, BlockContext
10 from django.utils.datastructures import SortedDict
11 from philo.models.base import TreeModel, register_value_model
12 from philo.models.fields import TemplateField
13 from philo.models.nodes import View
14 from philo.templatetags.containers import ContainerNode
15 from philo.utils import fattr
16 from philo.validators import LOADED_TEMPLATE_ATTR
17 from philo.signals import page_about_to_render_to_string, page_finished_rendering_to_string
20 class LazyContainerFinder(object):
21 def __init__(self, nodes):
23 self.initialized = False
24 self.contentlet_specs = set()
25 self.contentreference_specs = SortedDict()
27 self.block_super = False
29 def process(self, nodelist):
31 if isinstance(node, ContainerNode):
32 if not node.references:
33 self.contentlet_specs.add(node.name)
35 if node.name not in self.contentreference_specs.keys():
36 self.contentreference_specs[node.name] = node.references
39 if isinstance(node, BlockNode):
40 self.blocks[node.name] = block = LazyContainerFinder(node.nodelist)
42 self.blocks.update(block.blocks)
45 if isinstance(node, ExtendsNode):
48 if isinstance(node, VariableNode):
49 if node.filter_expression.var.lookups == (u'block', u'super'):
50 self.block_super = True
52 if hasattr(node, 'child_nodelists'):
53 for nodelist_name in node.child_nodelists:
54 if hasattr(node, nodelist_name):
55 nodelist = getattr(node, nodelist_name)
56 self.process(nodelist)
58 # LOADED_TEMPLATE_ATTR contains the name of an attribute philo uses to declare a
59 # node as rendering an additional template. Philo monkeypatches the attribute onto
60 # the relevant default nodes and declares it on any native nodes.
61 if hasattr(node, LOADED_TEMPLATE_ATTR):
62 loaded_template = getattr(node, LOADED_TEMPLATE_ATTR)
64 nodelist = loaded_template.nodelist
65 self.process(nodelist)
68 if not self.initialized:
69 self.process(self.nodes)
70 self.initialized = True
73 class Template(TreeModel):
74 name = models.CharField(max_length=255)
75 documentation = models.TextField(null=True, blank=True)
76 mimetype = models.CharField(max_length=255, default=getattr(settings, 'DEFAULT_CONTENT_TYPE', 'text/html'))
77 code = TemplateField(secure=False, verbose_name='django template code')
82 Returns a tuple where the first item is a list of names of contentlets referenced by containers,
83 and the second item is a list of tuples of names and contenttypes of contentreferences referenced by containers.
84 This will break if there is a recursive extends or includes in the template code.
85 Due to the use of an empty Context, any extends or include tags with dynamic arguments probably won't work.
87 template = DjangoTemplate(self.code)
89 def build_extension_tree(nodelist):
93 if not isinstance(node, TextNode):
94 if isinstance(node, ExtendsNode):
100 nodelists.append(LazyContainerFinder(extends.nodelist))
101 loaded_template = getattr(extends, LOADED_TEMPLATE_ATTR)
102 nodelists.extend(build_extension_tree(loaded_template.nodelist))
105 nodelists.append(LazyContainerFinder(nodelist))
108 # Build a tree of the templates we're using, placing the root template first.
109 levels = build_extension_tree(template.nodelist)[::-1]
111 contentlet_specs = set()
112 contentreference_specs = SortedDict()
117 contentlet_specs |= level.contentlet_specs
118 contentreference_specs.update(level.contentreference_specs)
119 for name, block in level.blocks.items():
120 if block.block_super:
121 blocks.setdefault(name, []).append(block)
123 blocks[name] = [block]
125 for block_list in blocks.values():
126 for block in block_list:
128 contentlet_specs |= block.contentlet_specs
129 contentreference_specs.update(block.contentreference_specs)
131 return contentlet_specs, contentreference_specs
133 def __unicode__(self):
134 return self.get_path(pathsep=u' › ', field='name')
142 Represents a page - something which is rendered according to a template. The page will have a number of related Contentlets depending on the template selected - but these will appear only after the page has been saved with that template.
144 template = models.ForeignKey(Template, related_name='pages')
145 title = models.CharField(max_length=255)
147 def get_containers(self):
148 if not hasattr(self, '_containers'):
149 self._containers = self.template.containers
150 return self._containers
151 containers = property(get_containers)
153 def render_to_string(self, request=None, extra_context=None):
155 context.update(extra_context or {})
156 context.update({'page': self, 'attributes': self.attributes})
157 template = DjangoTemplate(self.template.code)
159 context.update({'node': request.node, 'attributes': self.attributes_with_node(request.node)})
160 page_about_to_render_to_string.send(sender=self, request=request, extra_context=context)
161 string = template.render(RequestContext(request, context))
163 page_about_to_render_to_string.send(sender=self, request=request, extra_context=context)
164 string = template.render(Context(context))
165 page_finished_rendering_to_string.send(sender=self, string=string)
168 def actually_render_to_response(self, request, extra_context=None):
169 return HttpResponse(self.render_to_string(request, extra_context), mimetype=self.template.mimetype)
171 def __unicode__(self):
174 def clean_fields(self, exclude=None):
176 super(Page, self).clean_fields(exclude)
177 except ValidationError, e:
178 errors = e.message_dict
182 if 'template' not in errors and 'template' not in exclude:
184 self.template.clean_fields()
185 self.template.clean()
186 except ValidationError, e:
187 errors['template'] = e.messages
190 raise ValidationError(errors)
196 class Contentlet(models.Model):
197 page = models.ForeignKey(Page, related_name='contentlets')
198 name = models.CharField(max_length=255, db_index=True)
199 content = TemplateField()
201 def __unicode__(self):
208 class ContentReference(models.Model):
209 page = models.ForeignKey(Page, related_name='contentreferences')
210 name = models.CharField(max_length=255, db_index=True)
211 content_type = models.ForeignKey(ContentType, verbose_name='Content type')
212 content_id = models.PositiveIntegerField(verbose_name='Content ID', blank=True, null=True)
213 content = generic.GenericForeignKey('content_type', 'content_id')
215 def __unicode__(self):
222 register_templatetags('philo.templatetags.containers')
225 register_value_model(Template)
226 register_value_model(Page)