b9e481ba1356ff52aef543def7a2001c0471e613
[philo.git] / models / pages.py
1 # encoding: utf-8
2 from django.db import models
3 from django.contrib.contenttypes.models import ContentType
4 from django.contrib.contenttypes import generic
5 from django.conf import settings
6 from django.template import add_to_builtins as register_templatetags
7 from django.template import Template as DjangoTemplate
8 from django.template import TemplateDoesNotExist
9 from django.template import Context, RequestContext
10 from django.template.loader import get_template
11 from django.template.loader_tags import ExtendsNode, ConstantIncludeNode, IncludeNode
12 from django.http import HttpResponse
13 from philo.models.base import TreeModel, register_value_model
14 from philo.models.nodes import View
15 from philo.utils import fattr
16 from philo.templatetags.containers import ContainerNode
17
18
19 class Template(TreeModel):
20         name = models.CharField(max_length=255)
21         documentation = models.TextField(null=True, blank=True)
22         mimetype = models.CharField(max_length=255, null=True, blank=True, help_text='Default: %s' % settings.DEFAULT_CONTENT_TYPE)
23         code = models.TextField(verbose_name='django template code')
24         
25         @property
26         def origin(self):
27                 return 'philo.models.Template: ' + self.path
28         
29         @property
30         def django_template(self):
31                 return DjangoTemplate(self.code)
32         
33         @property
34         def containers(self):
35                 """
36                 Returns a tuple where the first item is a list of names of contentlets referenced by containers,
37                 and the second item is a list of tuples of names and contenttypes of contentreferences referenced by containers.
38                 This will break if there is a recursive extends or includes in the template code.
39                 Due to the use of an empty Context, any extends or include tags with dynamic arguments probably won't work.
40                 """
41                 def container_nodes(template):
42                         def nodelist_container_nodes(nodelist):
43                                 nodes = []
44                                 for node in nodelist:
45                                         try:
46                                                 for nodelist_name in ('nodelist', 'nodelist_loop', 'nodelist_empty', 'nodelist_true', 'nodelist_false', 'nodelist_main'):
47                                                         if hasattr(node, nodelist_name):
48                                                                 nodes.extend(nodelist_container_nodes(getattr(node, nodelist_name)))
49                                                 if isinstance(node, ContainerNode):
50                                                         nodes.append(node)
51                                                 elif isinstance(node, ExtendsNode):
52                                                         extended_template = node.get_parent(Context())
53                                                         if extended_template:
54                                                                 nodes.extend(container_nodes(extended_template))
55                                                 elif isinstance(node, ConstantIncludeNode):
56                                                         included_template = node.template
57                                                         if included_template:
58                                                                 nodes.extend(container_nodes(included_template))
59                                                 elif isinstance(node, IncludeNode):
60                                                         included_template = get_template(node.template_name.resolve(Context()))
61                                                         if included_template:
62                                                                 nodes.extend(container_nodes(included_template))
63                                         except:
64                                                 raise # fail for this node
65                                 return nodes
66                         return nodelist_container_nodes(template.nodelist)
67                 all_nodes = container_nodes(self.django_template)
68                 contentlet_node_names = set([node.name for node in all_nodes if not node.references])
69                 contentreference_node_names = []
70                 contentreference_node_specs = []
71                 for node in all_nodes:
72                         if node.references and node.name not in contentreference_node_names:
73                                 contentreference_node_specs.append((node.name, node.references))
74                                 contentreference_node_names.append(node.name)
75                 return contentlet_node_names, contentreference_node_specs
76         
77         def __unicode__(self):
78                 return self.get_path(u' › ', 'name')
79         
80         @staticmethod
81         @fattr(is_usable=True)
82         def loader(template_name, template_dirs=None): # load_template_source
83                 try:
84                         template = Template.objects.get_with_path(template_name)
85                 except Template.DoesNotExist:
86                         raise TemplateDoesNotExist(template_name)
87                 return (template.code, template.origin)
88         
89         class Meta:
90                 app_label = 'philo'
91
92
93 class Page(View):
94         """
95         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.
96         """
97         template = models.ForeignKey(Template, related_name='pages')
98         title = models.CharField(max_length=255)
99         
100         def render_to_response(self, node, request, path=None, subpath=None):
101                 return HttpResponse(self.template.django_template.render(RequestContext(request, {'page': self})), mimetype=self.template.mimetype)
102         
103         def __unicode__(self):
104                 return self.title
105         
106         class Meta:
107                 app_label = 'philo'
108
109
110 class Contentlet(models.Model):
111         page = models.ForeignKey(Page, related_name='contentlets')
112         name = models.CharField(max_length=255)
113         content = models.TextField()
114         dynamic = models.BooleanField(default=False)
115         
116         def __unicode__(self):
117                 return self.name
118         
119         class Meta:
120                 app_label = 'philo'
121
122
123 class ContentReference(models.Model):
124         page = models.ForeignKey(Page, related_name='contentreferences')
125         name = models.CharField(max_length=255)
126         content_type = models.ForeignKey(ContentType, verbose_name='Content type')
127         content_id = models.PositiveIntegerField(verbose_name='Content ID', blank=True, null=True)
128         content = generic.GenericForeignKey('content_type', 'content_id')
129         
130         def __unicode__(self):
131                 return self.name
132         
133         class Meta:
134                 app_label = 'philo'
135
136
137 register_templatetags('philo.templatetags.containers')
138
139
140 register_value_model(Template)
141 register_value_model(Page)