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
20 _view_content_type_limiter = ContentTypeSubclassLimiter(None)
21 DEFAULT_NAVIGATION_DEPTH = 3
24 class Node(TreeEntity):
25 view_content_type = models.ForeignKey(ContentType, related_name='node_view_set', limit_choices_to=_view_content_type_limiter)
26 view_object_id = models.PositiveIntegerField()
27 view = generic.GenericForeignKey('view_content_type', 'view_object_id')
30 def accepts_subpath(self):
32 return self.view.accepts_subpath
35 def render_to_response(self, request, extra_context=None):
36 return self.view.render_to_response(request, extra_context)
38 def get_absolute_url(self):
40 root = Site.objects.get_current().root_node
41 except Site.DoesNotExist:
45 path = self.get_path(root=root)
48 root_url = reverse('philo-root')
49 return '%s%s' % (root_url, path)
50 except AncestorDoesNotExist, ViewDoesNotExist:
53 def get_navigation(self, depth=DEFAULT_NAVIGATION_DEPTH, current_depth=0, found_node_pks=None):
54 navigation = self.view.get_navigation(self, depth, current_depth)
56 if depth == current_depth:
60 found_node_pks = found_node_pks or [self.pk]
61 ordered_child_pks = NodeNavigationOverride.objects.filter(parent=self, child__parent=self).values_list('child__pk', flat=True)
63 children = self.children.exclude(pk__in=found_node_pks)
64 ordered_children = children.filter(pk__in=ordered_child_pks)
65 unordered_children = children.exclude(pk__in=ordered_child_pks)
67 children = list(ordered_children) + list(unordered_children)
71 for child in children:
72 found_node_pks.append(child.pk)
74 child_navigation.append(child.get_navigation(depth, current_depth + 1, found_node_pks))
75 except NotImplementedError:
79 if 'children' in navigation:
80 navigation['children'] += child_navigation
82 navigation['children'] = child_navigation
87 super(Node, self).save()
94 # the following line enables the selection of a node as the root for a given django.contrib.sites Site object
95 models.ForeignKey(Node, related_name='sites', null=True, blank=True).contribute_to_class(Site, 'root_node')
98 class NodeNavigationOverride(Entity):
99 parent = models.ForeignKey(Node, related_name="navigation_override_child_set")
100 child = models.OneToOneField(Node, related_name="navigation_override")
101 url = models.CharField(max_length=200, validators=[RedirectValidator()], blank=True)
102 title = models.CharField(max_length=100, blank=True)
103 order = models.PositiveSmallIntegerField(blank=True, null=True)
104 child_navigation = JSONField()
106 def get_navigation(self, node, depth, current_depth):
107 if self.child_navigation:
108 depth = current_depth
109 default = node.get_navigation(depth, current_depth)
111 default['url'] = self.url
113 default['title'] = self.title
114 if self.child_navigation:
115 if 'children' in default:
116 default['children'] += self.child_navigation
118 default['children'] = self.child_navigation
125 nodes = generic.GenericRelation(Node, content_type_field='view_content_type', object_id_field='view_object_id')
127 accepts_subpath = False
129 def get_subpath(self, obj):
130 if not self.accepts_subpath:
131 raise ViewDoesNotProvideSubpaths
133 view_name, args, kwargs = self.get_reverse_params(obj)
135 return reverse(view_name, args=args, kwargs=kwargs, urlconf=self)
136 except NoReverseMatch:
137 raise ViewCanNotProvideSubpath
139 def get_reverse_params(self, obj):
140 """This method should return a view_name, args, kwargs tuple suitable for reversing a url for the given obj using self as the urlconf."""
141 raise NotImplementedError("View subclasses must implement get_reverse_params to support subpaths.")
143 def attributes_with_node(self, node):
144 return QuerySetMapper(self.attribute_set, passthrough=node.attributes)
146 def render_to_response(self, request, extra_context=None):
147 if not hasattr(request, 'node'):
148 raise MIDDLEWARE_NOT_CONFIGURED
150 extra_context = extra_context or {}
151 view_about_to_render.send(sender=self, request=request, extra_context=extra_context)
152 response = self.actually_render_to_response(request, extra_context)
153 view_finished_rendering.send(sender=self, response=response)
156 def actually_render_to_response(self, request, extra_context=None):
157 raise NotImplementedError('View subclasses must implement render_to_response.')
159 def get_navigation(self, node, depth, current_depth):
160 raise NotImplementedError('View subclasses must implement get_navigation.')
166 _view_content_type_limiter.cls = View
169 class MultiView(View):
170 accepts_subpath = True
173 def urlpatterns(self, obj):
174 raise NotImplementedError("MultiView subclasses must implement urlpatterns.")
176 def actually_render_to_response(self, request, extra_context=None):
178 subpath = request.node.subpath
181 subpath = "/" + subpath
182 view, args, kwargs = resolve(subpath, urlconf=self)
183 view_args = getargspec(view)
184 if extra_context is not None and ('extra_context' in view_args[0] or view_args[2] is not None):
185 if 'extra_context' in kwargs:
186 extra_context.update(kwargs['extra_context'])
187 kwargs['extra_context'] = extra_context
188 return view(request, *args, **kwargs)
194 class Redirect(View):
199 target = models.CharField(max_length=200, validators=[RedirectValidator()])
200 status_code = models.IntegerField(choices=STATUS_CODES, default=302, verbose_name='redirect type')
202 def actually_render_to_response(self, request, extra_context=None):
203 response = HttpResponseRedirect(self.target)
204 response.status_code = self.status_code
211 # Why does this exist?
213 """ For storing arbitrary files """
215 mimetype = models.CharField(max_length=255)
216 file = models.FileField(upload_to='philo/files/%Y/%m/%d')
218 def actually_render_to_response(self, request, extra_context=None):
219 wrapper = FileWrapper(self.file)
220 response = HttpResponse(wrapper, content_type=self.mimetype)
221 response['Content-Length'] = self.file.size
227 def __unicode__(self):
228 return self.file.name
231 register_templatetags('philo.templatetags.nodes')
232 register_value_model(Node)