Added basic docs for entities and attributes.
[philo.git] / utils.py
1 from django.db import models
2 from django.contrib.contenttypes.models import ContentType
3 from django.core.paginator import Paginator, EmptyPage
4 from django.template import Context
5 from django.template.loader_tags import ExtendsNode, ConstantIncludeNode
6
7
8 class ContentTypeLimiter(object):
9         def q_object(self):
10                 return models.Q(pk__in=[])
11         
12         def add_to_query(self, query, *args, **kwargs):
13                 query.add_q(self.q_object(), *args, **kwargs)
14
15
16 class ContentTypeRegistryLimiter(ContentTypeLimiter):
17         def __init__(self):
18                 self.classes = []
19         
20         def register_class(self, cls):
21                 self.classes.append(cls)
22         
23         def unregister_class(self, cls):
24                 self.classes.remove(cls)
25         
26         def q_object(self):
27                 contenttype_pks = []
28                 for cls in self.classes:
29                         try:
30                                 if issubclass(cls, models.Model):
31                                         if not cls._meta.abstract:
32                                                 contenttype = ContentType.objects.get_for_model(cls)
33                                                 contenttype_pks.append(contenttype.pk)
34                         except:
35                                 pass
36                 return models.Q(pk__in=contenttype_pks)
37
38
39 class ContentTypeSubclassLimiter(ContentTypeLimiter):
40         def __init__(self, cls, inclusive=False):
41                 self.cls = cls
42                 self.inclusive = inclusive
43         
44         def q_object(self):
45                 contenttype_pks = []
46                 def handle_subclasses(cls):
47                         for subclass in cls.__subclasses__():
48                                 try:
49                                         if issubclass(subclass, models.Model):
50                                                 if not subclass._meta.abstract:
51                                                         if not self.inclusive and subclass is self.cls:
52                                                                 continue
53                                                         contenttype = ContentType.objects.get_for_model(subclass)
54                                                         contenttype_pks.append(contenttype.pk)
55                                         handle_subclasses(subclass)
56                                 except:
57                                         pass
58                 handle_subclasses(self.cls)
59                 return models.Q(pk__in=contenttype_pks)
60
61
62 def fattr(*args, **kwargs):
63         def wrapper(function):
64                 for key in kwargs:
65                         setattr(function, key, kwargs[key])
66                 return function
67         return wrapper
68
69
70 def paginate(objects, per_page=None, page_number=1):
71         """
72         Given a list of objects, return a (paginator, page, objects) tuple.
73         """
74         try:
75                 per_page = int(per_page)
76         except (TypeError, ValueError):
77                 # Then either it wasn't set or it was set to an invalid value
78                 paginator = page = None
79         else:
80                 # There also shouldn't be pagination if the list is too short. Try count()
81                 # first - good chance it's a queryset, where count is more efficient.
82                 try:
83                         if objects.count() <= per_page:
84                                 paginator = page = None
85                 except AttributeError:
86                         if len(objects) <= per_page:
87                                 paginator = page = None
88         
89         try:
90                 return paginator, page, objects
91         except NameError:
92                 pass
93         
94         paginator = Paginator(objects, per_page)
95         try:
96                 page_number = int(page_number)
97         except:
98                 page_number = 1
99         
100         try:
101                 page = paginator.page(page_number)
102         except EmptyPage:
103                 page = None
104         else:
105                 objects = page.object_list
106         
107         return paginator, page, objects
108
109
110 LOADED_TEMPLATE_ATTR = '_philo_loaded_template'
111 BLANK_CONTEXT = Context()
112
113
114 def get_extended(self):
115         return self.get_parent(BLANK_CONTEXT)
116
117
118 def get_included(self):
119         return self.template
120
121
122 # We ignore the IncludeNode because it will never work in a blank context.
123 setattr(ExtendsNode, LOADED_TEMPLATE_ATTR, property(get_extended))
124 setattr(ConstantIncludeNode, LOADED_TEMPLATE_ATTR, property(get_included))
125
126
127 def nodelist_crawl(nodelist, callback):
128         """This function crawls through a template's nodelist and the nodelists of any included or extended
129         templates, as determined by the presence and value of <LOADED_TEMPLATE_ATTR> on a node. Each node
130         will also be passed to a callback function for additional processing."""
131         results = []
132         for node in nodelist:
133                 try:
134                         if hasattr(node, 'child_nodelists'):
135                                 for nodelist_name in node.child_nodelists:
136                                         if hasattr(node, nodelist_name):
137                                                 results.extend(nodelist_crawl(getattr(node, nodelist_name), callback))
138                         
139                         # LOADED_TEMPLATE_ATTR contains the name of an attribute philo uses to declare a
140                         # node as rendering an additional template. Philo monkeypatches the attribute onto
141                         # the relevant default nodes and declares it on any native nodes.
142                         if hasattr(node, LOADED_TEMPLATE_ATTR):
143                                 loaded_template = getattr(node, LOADED_TEMPLATE_ATTR)
144                                 if loaded_template:
145                                         results.extend(nodelist_crawl(loaded_template.nodelist, callback))
146                         
147                         callback(node, results)
148                 except:
149                         raise # fail for this node
150         return results