1 from django.db import models
2 from django.contrib.contenttypes.models import ContentType
3 from django.contrib.contenttypes import generic
4 from django.contrib.sites.models import Site
5 from django.http import HttpResponse, HttpResponseServerError, HttpResponseRedirect
6 from django.core.exceptions import ViewDoesNotExist
7 from django.core.servers.basehttp import FileWrapper
8 from django.core.urlresolvers import resolve, clear_url_caches, reverse, NoReverseMatch
9 from django.template import add_to_builtins as register_templatetags
10 from inspect import getargspec
11 from philo.exceptions import MIDDLEWARE_NOT_CONFIGURED
12 from philo.models.base import TreeEntity, Entity, QuerySetMapper, register_value_model
13 from philo.models.fields import JSONField
14 from philo.utils import ContentTypeSubclassLimiter
15 from philo.validators import RedirectValidator
16 from philo.exceptions import ViewCanNotProvideSubpath, ViewDoesNotProvideSubpaths, AncestorDoesNotExist
17 from philo.signals import view_about_to_render, view_finished_rendering
18 from mptt.templatetags.mptt_tags import cache_tree_children
21 _view_content_type_limiter = ContentTypeSubclassLimiter(None)
22 DEFAULT_NAVIGATION_DEPTH = 3
25 class Node(TreeEntity):
26 view_content_type = models.ForeignKey(ContentType, related_name='node_view_set', limit_choices_to=_view_content_type_limiter)
27 view_object_id = models.PositiveIntegerField()
28 view = generic.GenericForeignKey('view_content_type', 'view_object_id')
31 def accepts_subpath(self):
33 return self.view.accepts_subpath
36 def render_to_response(self, request, extra_context=None):
37 return self.view.render_to_response(request, extra_context)
39 def get_absolute_url(self):
41 root = Site.objects.get_current().root_node
42 except Site.DoesNotExist:
46 path = self.get_path(root=root)
49 root_url = reverse('philo-root')
50 return '%s%s' % (root_url, path)
51 except AncestorDoesNotExist, ViewDoesNotExist:
54 def get_navigation(self, depth=DEFAULT_NAVIGATION_DEPTH):
55 max_depth = depth + self.get_level()
56 tree = cache_tree_children(self.get_descendants(include_self=True).filter(level__lte=max_depth))
58 def get_nav(parent, nodes):
59 node_overrides = dict([(override.child.pk, override) for override in NodeNavigationOverride.objects.filter(parent=parent, child__in=nodes).select_related('child')])
63 node._override = node_overrides.get(node.pk, None)
66 if node._override.hide:
68 navigation = node._override.get_navigation(node, max_depth)
70 navigation = node.view.get_navigation(node, max_depth)
72 if not node.is_leaf_node() and node.get_level() < max_depth:
73 children = navigation.get('children', [])
74 children += get_nav(node, node.get_children())
75 navigation['children'] = children
77 if 'children' in navigation:
78 navigation['children'].sort(cmp=lambda x,y: cmp(x['order'], y['order']))
80 navigation_list.append(navigation)
82 return navigation_list
84 navigation = get_nav(self.parent, tree)
86 navigation = [root] + root['children']
91 super(Node, self).save()
98 # the following line enables the selection of a node as the root for a given django.contrib.sites Site object
99 models.ForeignKey(Node, related_name='sites', null=True, blank=True).contribute_to_class(Site, 'root_node')
102 class NodeNavigationOverride(Entity):
103 parent = models.ForeignKey(Node, related_name="child_navigation_overrides", blank=True, null=True)
104 child = models.ForeignKey(Node, related_name="navigation_overrides")
106 title = models.CharField(max_length=100, blank=True)
107 url = models.CharField(max_length=200, validators=[RedirectValidator()], blank=True)
108 order = models.PositiveSmallIntegerField(blank=True, null=True)
109 child_navigation = JSONField()
110 hide = models.BooleanField()
112 def get_navigation(self, node, max_depth):
113 default = node.view.get_navigation(node, max_depth)
115 default['url'] = self.url
117 default['title'] = self.title
119 default['order'] = self.order
120 if isinstance(self.child_navigation, list) and node.get_level() < max_depth:
121 child_navigation = self.child_navigation[:]
123 for child in child_navigation:
124 child['url'] = default['url'] + child['url']
126 if 'children' in default:
127 overridden = set([child['url'] for child in default['children']]) & set([child['url'] for child in self.child_navigation])
129 for child in default[:]:
130 if child['url'] in overridden:
131 default.remove(child)
132 default['children'] += self.child_navigation
134 default['children'] = self.child_navigation
139 unique_together = ('parent', 'child',)
144 nodes = generic.GenericRelation(Node, content_type_field='view_content_type', object_id_field='view_object_id')
146 accepts_subpath = False
148 def get_subpath(self, obj):
149 if not self.accepts_subpath:
150 raise ViewDoesNotProvideSubpaths
152 view_name, args, kwargs = self.get_reverse_params(obj)
154 return reverse(view_name, args=args, kwargs=kwargs, urlconf=self)
155 except NoReverseMatch:
156 raise ViewCanNotProvideSubpath
158 def get_reverse_params(self, obj):
159 """This method should return a view_name, args, kwargs tuple suitable for reversing a url for the given obj using self as the urlconf."""
160 raise NotImplementedError("View subclasses must implement get_reverse_params to support subpaths.")
162 def attributes_with_node(self, node):
163 return QuerySetMapper(self.attribute_set, passthrough=node.attributes)
165 def render_to_response(self, request, extra_context=None):
166 if not hasattr(request, 'node'):
167 raise MIDDLEWARE_NOT_CONFIGURED
169 extra_context = extra_context or {}
170 view_about_to_render.send(sender=self, request=request, extra_context=extra_context)
171 response = self.actually_render_to_response(request, extra_context)
172 view_finished_rendering.send(sender=self, response=response)
175 def actually_render_to_response(self, request, extra_context=None):
176 raise NotImplementedError('View subclasses must implement render_to_response.')
178 def get_navigation(self, node, max_depth):
180 Subclasses should implement get_navigation to support auto-generated navigation.
181 max_depth is the deepest `level` that should be generated; node is the node that
182 is asking for the navigation. This method should return a dictionary of the form:
186 'order': order, # None for no ordering.
187 'children': [ # Optional
188 <similar child navigation dictionaries>
192 raise NotImplementedError('View subclasses must implement get_navigation.')
198 _view_content_type_limiter.cls = View
201 class MultiView(View):
202 accepts_subpath = True
205 def urlpatterns(self, obj):
206 raise NotImplementedError("MultiView subclasses must implement urlpatterns.")
208 def actually_render_to_response(self, request, extra_context=None):
210 subpath = request.node.subpath
213 subpath = "/" + subpath
214 view, args, kwargs = resolve(subpath, urlconf=self)
215 view_args = getargspec(view)
216 if extra_context is not None and ('extra_context' in view_args[0] or view_args[2] is not None):
217 if 'extra_context' in kwargs:
218 extra_context.update(kwargs['extra_context'])
219 kwargs['extra_context'] = extra_context
220 return view(request, *args, **kwargs)
226 class Redirect(View):
231 target = models.CharField(max_length=200, validators=[RedirectValidator()])
232 status_code = models.IntegerField(choices=STATUS_CODES, default=302, verbose_name='redirect type')
234 def actually_render_to_response(self, request, extra_context=None):
235 response = HttpResponseRedirect(self.target)
236 response.status_code = self.status_code
243 # Why does this exist?
245 """ For storing arbitrary files """
247 mimetype = models.CharField(max_length=255)
248 file = models.FileField(upload_to='philo/files/%Y/%m/%d')
250 def actually_render_to_response(self, request, extra_context=None):
251 wrapper = FileWrapper(self.file)
252 response = HttpResponse(wrapper, content_type=self.mimetype)
253 response['Content-Length'] = self.file.size
259 def __unicode__(self):
260 return self.file.name
263 register_templatetags('philo.templatetags.nodes')
264 register_value_model(Node)