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.utils import ContentTypeSubclassLimiter
14 from philo.validators import RedirectValidator
15 from philo.exceptions import ViewCanNotProvideSubpath, ViewDoesNotProvideSubpaths, AncestorDoesNotExist
16 from philo.signals import view_about_to_render, view_finished_rendering
19 _view_content_type_limiter = ContentTypeSubclassLimiter(None)
22 class Node(TreeEntity):
23 view_content_type = models.ForeignKey(ContentType, related_name='node_view_set', limit_choices_to=_view_content_type_limiter)
24 view_object_id = models.PositiveIntegerField()
25 view = generic.GenericForeignKey('view_content_type', 'view_object_id')
28 def accepts_subpath(self):
30 return self.view.accepts_subpath
33 def render_to_response(self, request, extra_context=None):
34 return self.view.render_to_response(request, extra_context)
36 def get_absolute_url(self):
38 root = Site.objects.get_current().root_node
39 except Site.DoesNotExist:
43 path = self.get_path(root=root)
46 root_url = reverse('philo-root')
47 return '%s%s' % (root_url, path)
48 except AncestorDoesNotExist, ViewDoesNotExist:
55 # the following line enables the selection of a node as the root for a given django.contrib.sites Site object
56 models.ForeignKey(Node, related_name='sites', null=True, blank=True).contribute_to_class(Site, 'root_node')
60 nodes = generic.GenericRelation(Node, content_type_field='view_content_type', object_id_field='view_object_id')
62 accepts_subpath = False
64 def get_subpath(self, obj):
65 if not self.accepts_subpath:
66 raise ViewDoesNotProvideSubpaths
68 view_name, args, kwargs = self.get_reverse_params(obj)
70 return reverse(view_name, args=args, kwargs=kwargs, urlconf=self)
71 except NoReverseMatch:
72 raise ViewCanNotProvideSubpath
74 def get_reverse_params(self, obj):
75 """This method should return a view_name, args, kwargs tuple suitable for reversing a url for the given obj using self as the urlconf."""
76 raise NotImplementedError("View subclasses must implement get_reverse_params to support subpaths.")
78 def attributes_with_node(self, node):
79 return QuerySetMapper(self.attribute_set, passthrough=node.attributes)
81 def render_to_response(self, request, extra_context=None):
82 if not hasattr(request, 'node'):
83 raise MIDDLEWARE_NOT_CONFIGURED
85 extra_context = extra_context or {}
86 view_about_to_render.send(sender=self, request=request, extra_context=extra_context)
87 response = self.actually_render_to_response(request, extra_context)
88 view_finished_rendering.send(sender=self, response=response)
91 def actually_render_to_response(self, request, extra_context=None):
92 raise NotImplementedError('View subclasses must implement render_to_response.')
98 _view_content_type_limiter.cls = View
101 class MultiView(View):
102 accepts_subpath = True
105 def urlpatterns(self, obj):
106 raise NotImplementedError("MultiView subclasses must implement urlpatterns.")
108 def actually_render_to_response(self, request, extra_context=None):
110 subpath = request.node.subpath
113 subpath = "/" + subpath
114 view, args, kwargs = resolve(subpath, urlconf=self)
115 view_args = getargspec(view)
116 if extra_context is not None and ('extra_context' in view_args[0] or view_args[2] is not None):
117 if 'extra_context' in kwargs:
118 extra_context.update(kwargs['extra_context'])
119 kwargs['extra_context'] = extra_context
120 return view(request, *args, **kwargs)
122 def reverse(self, view_name, args=None, kwargs=None, node=None):
123 """Shortcut method to handle the common pattern of getting the absolute url for a multiview's
125 subpath = reverse(view_name, urlconf=self, args=args or [], kwargs=kwargs or {})
127 return '/%s/%s/' % (node.get_absolute_url().strip('/'), subpath.strip('/'))
130 def get_context(self):
131 """Hook for providing instance-specific context - such as the value of a Field - to all views."""
134 def basic_view(self, view_name):
136 Wraps a field name and returns a simple view function that will render that view
137 with a basic context. This assumes that the field name is a ForeignKey to a
138 model with a render_to_response method.
140 field = self._meta.get_field(view_name)
141 view = getattr(self, field.name, None)
143 def inner(request, extra_context=None, **kwargs):
146 context = self.get_context()
147 context.update(extra_context or {})
148 return view.render_to_response(request, extra_context=context)
156 class Redirect(View):
161 target = models.CharField(max_length=200, validators=[RedirectValidator()])
162 status_code = models.IntegerField(choices=STATUS_CODES, default=302, verbose_name='redirect type')
164 def actually_render_to_response(self, request, extra_context=None):
165 response = HttpResponseRedirect(self.target)
166 response.status_code = self.status_code
173 # Why does this exist?
175 """ For storing arbitrary files """
177 mimetype = models.CharField(max_length=255)
178 file = models.FileField(upload_to='philo/files/%Y/%m/%d')
180 def actually_render_to_response(self, request, extra_context=None):
181 wrapper = FileWrapper(self.file)
182 response = HttpResponse(wrapper, content_type=self.mimetype)
183 response['Content-Length'] = self.file.size
189 def __unicode__(self):
190 return self.file.name
193 register_templatetags('philo.templatetags.nodes')
194 register_value_model(Node)