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
8 class ContentTypeLimiter(object):
10 return models.Q(pk__in=[])
12 def add_to_query(self, query, *args, **kwargs):
13 query.add_q(self.q_object(), *args, **kwargs)
16 class ContentTypeRegistryLimiter(ContentTypeLimiter):
20 def register_class(self, cls):
21 self.classes.append(cls)
23 def unregister_class(self, cls):
24 self.classes.remove(cls)
28 for cls in self.classes:
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)
36 return models.Q(pk__in=contenttype_pks)
39 class ContentTypeSubclassLimiter(ContentTypeLimiter):
40 def __init__(self, cls, inclusive=False):
42 self.inclusive = inclusive
46 def handle_subclasses(cls):
47 for subclass in cls.__subclasses__():
49 if issubclass(subclass, models.Model):
50 if not subclass._meta.abstract:
51 if not self.inclusive and subclass is self.cls:
53 contenttype = ContentType.objects.get_for_model(subclass)
54 contenttype_pks.append(contenttype.pk)
55 handle_subclasses(subclass)
58 handle_subclasses(self.cls)
59 return models.Q(pk__in=contenttype_pks)
62 def fattr(*args, **kwargs):
63 def wrapper(function):
65 setattr(function, key, kwargs[key])
70 def paginate(objects, per_page=None, page_number=1):
72 Given a list of objects, return a (paginator, page, objects) tuple.
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
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.
83 if objects.count() <= per_page:
84 paginator = page = None
85 except AttributeError:
86 if len(objects) <= per_page:
87 paginator = page = None
90 return paginator, page, objects
94 paginator = Paginator(objects, per_page)
96 page_number = int(page_number)
101 page = paginator.page(page_number)
105 objects = page.object_list
107 return paginator, page, objects
110 LOADED_TEMPLATE_ATTR = '_philo_loaded_template'
111 BLANK_CONTEXT = Context()
114 def get_extended(self):
115 return self.get_parent(BLANK_CONTEXT)
118 def get_included(self):
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))