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, RequestSite
5 from django.http import HttpResponse, HttpResponseServerError, HttpResponseRedirect, Http404
6 from django.core.exceptions import ValidationError
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)
23 class Node(TreeEntity):
24 view_content_type = models.ForeignKey(ContentType, related_name='node_view_set', limit_choices_to=_view_content_type_limiter)
25 view_object_id = models.PositiveIntegerField()
26 view = generic.GenericForeignKey('view_content_type', 'view_object_id')
29 def accepts_subpath(self):
31 return self.view.accepts_subpath
34 def handles_subpath(self, subpath):
35 return self.view.handles_subpath(subpath)
37 def render_to_response(self, request, extra_context=None):
38 return self.view.render_to_response(request, extra_context)
40 def get_absolute_url(self, request=None, with_domain=False, secure=False):
41 return self.construct_url(request=request, with_domain=with_domain, secure=secure)
43 def construct_url(self, subpath="/", request=None, with_domain=False, secure=False):
45 This method will construct a URL based on the Node's location.
46 If a request is passed in, that will be used as a backup in case
47 the Site lookup fails. The Site lookup takes precedence because
48 it's what's used to find the root node. This will raise:
49 - NoReverseMatch if philo-root is not reverseable
50 - Site.DoesNotExist if a domain is requested but not buildable.
51 - AncestorDoesNotExist if the root node of the site isn't an
52 ancestor of this instance.
54 # Try reversing philo-root first, since we can't do anything if that fails.
55 root_url = reverse('philo-root')
58 current_site = Site.objects.get_current()
59 except Site.DoesNotExist:
60 if request is not None:
61 current_site = RequestSite(request)
63 # If they want a domain and we can't figure one out,
64 # best to reraise the error to let them know.
69 root = getattr(current_site, 'root_node', None)
70 path = self.get_path(root=root)
72 if current_site and with_domain:
73 domain = "http%s://%s" % (secure and "s" or "", current_site.domain)
77 if not path or subpath == "/":
80 return '%s%s%s%s' % (domain, root_url, path, subpath)
86 # the following line enables the selection of a node as the root for a given django.contrib.sites Site object
87 models.ForeignKey(Node, related_name='sites', null=True, blank=True).contribute_to_class(Site, 'root_node')
91 nodes = generic.GenericRelation(Node, content_type_field='view_content_type', object_id_field='view_object_id')
93 accepts_subpath = False
95 def handles_subpath(self, subpath):
96 if not self.accepts_subpath and subpath != "/":
100 def reverse(self, view_name=None, args=None, kwargs=None, node=None, obj=None):
101 """Shortcut method to handle the common pattern of getting the
102 absolute url for a view's subpaths."""
103 if not self.accepts_subpath:
104 raise ViewDoesNotProvideSubpaths
107 # Perhaps just override instead of combining?
108 obj_view_name, obj_args, obj_kwargs = self.get_reverse_params(obj)
109 if view_name is None:
110 view_name = obj_view_name
111 args = list(obj_args) + list(args or [])
112 obj_kwargs.update(kwargs or {})
116 subpath = reverse(view_name, urlconf=self, args=args or [], kwargs=kwargs or {})
117 except NoReverseMatch:
118 raise ViewCanNotProvideSubpath
121 return node.construct_url(subpath)
124 def get_reverse_params(self, obj):
125 """This method should return a view_name, args, kwargs tuple suitable for reversing a url for the given obj using self as the urlconf."""
126 raise NotImplementedError("View subclasses must implement get_reverse_params to support subpaths.")
128 def attributes_with_node(self, node):
129 return QuerySetMapper(self.attribute_set, passthrough=node.attributes)
131 def render_to_response(self, request, extra_context=None):
132 if not hasattr(request, 'node'):
133 raise MIDDLEWARE_NOT_CONFIGURED
135 extra_context = extra_context or {}
136 view_about_to_render.send(sender=self, request=request, extra_context=extra_context)
137 response = self.actually_render_to_response(request, extra_context)
138 view_finished_rendering.send(sender=self, response=response)
141 def actually_render_to_response(self, request, extra_context=None):
142 raise NotImplementedError('View subclasses must implement actually_render_to_response.')
148 _view_content_type_limiter.cls = View
151 class MultiView(View):
152 accepts_subpath = True
155 def urlpatterns(self):
156 raise NotImplementedError("MultiView subclasses must implement urlpatterns.")
158 def handles_subpath(self, subpath):
159 if not super(MultiView, self).handles_subpath(subpath):
162 resolve(subpath, urlconf=self)
167 def actually_render_to_response(self, request, extra_context=None):
169 subpath = request.node.subpath
170 view, args, kwargs = resolve(subpath, urlconf=self)
171 view_args = getargspec(view)
172 if extra_context is not None and ('extra_context' in view_args[0] or view_args[2] is not None):
173 if 'extra_context' in kwargs:
174 extra_context.update(kwargs['extra_context'])
175 kwargs['extra_context'] = extra_context
176 return view(request, *args, **kwargs)
178 def get_context(self):
179 """Hook for providing instance-specific context - such as the value of a Field - to all views."""
182 def basic_view(self, field_name):
184 Given the name of a field on ``self``, accesses the value of
185 that field and treats it as a ``View`` instance. Creates a
186 basic context based on self.get_context() and any extra_context
187 that was passed in, then calls the ``View`` instance's
188 render_to_response() method. This method is meant to be called
189 to return a view function appropriate for urlpatterns.
191 field = self._meta.get_field(field_name)
192 view = getattr(self, field.name, None)
194 def inner(request, extra_context=None, **kwargs):
197 context = self.get_context()
198 context.update(extra_context or {})
199 return view.render_to_response(request, extra_context=context)
207 class TargetURLModel(models.Model):
208 target_node = models.ForeignKey(Node, blank=True, null=True, related_name="%(app_label)s_%(class)s_related")
209 url_or_subpath = models.CharField(max_length=200, validators=[RedirectValidator()], blank=True, help_text="Point to this url or, if a node is defined and accepts subpaths, this subpath of the node.")
210 reversing_parameters = JSONField(blank=True, help_text="If reversing parameters are defined, url_or_subpath will instead be interpreted as the view name to be reversed.")
213 # Should this be enforced? Not enforcing it would allow creation of "headers" in the navbar.
214 if not self.target_node and not self.url_or_subpath:
215 raise ValidationError("Either a target node or a url must be defined.")
217 if self.reversing_parameters and not (self.url_or_subpath or self.target_node):
218 raise ValidationError("Reversing parameters require either a view name or a target node.")
221 self.get_target_url()
222 except NoReverseMatch, e:
223 raise ValidationError(e.message)
225 super(TargetURLModel, self).clean()
227 def get_reverse_params(self):
228 params = self.reversing_parameters
229 args = isinstance(params, list) and params or None
230 kwargs = isinstance(params, dict) and params or None
231 return self.url_or_subpath, args, kwargs
233 def get_target_url(self):
234 node = self.target_node
235 if node is not None and node.accepts_subpath and self.url_or_subpath:
236 if self.reversing_parameters is not None:
237 view_name, args, kwargs = self.get_reverse_params()
238 subpath = node.view.reverse(view_name, args=args, kwargs=kwargs)
240 subpath = self.url_or_subpath
241 if subpath[0] != '/':
242 subpath = '/' + subpath
243 return node.construct_url(subpath)
244 elif node is not None:
245 return node.get_absolute_url()
247 if self.reversing_parameters is not None:
248 view_name, args, kwargs = self.get_reverse_params()
249 return reverse(view_name, args=args, kwargs=kwargs)
250 return self.url_or_subpath
251 target_url = property(get_target_url)
257 class Redirect(View, TargetURLModel):
262 status_code = models.IntegerField(choices=STATUS_CODES, default=302, verbose_name='redirect type')
264 def actually_render_to_response(self, request, extra_context=None):
265 response = HttpResponseRedirect(self.target_url)
266 response.status_code = self.status_code
274 """ For storing arbitrary files """
276 mimetype = models.CharField(max_length=255)
277 file = models.FileField(upload_to='philo/files/%Y/%m/%d')
279 def actually_render_to_response(self, request, extra_context=None):
280 wrapper = FileWrapper(self.file)
281 response = HttpResponse(wrapper, content_type=self.mimetype)
282 response['Content-Length'] = self.file.size
288 def __unicode__(self):
289 return self.file.name
292 register_templatetags('philo.templatetags.nodes')
293 register_value_model(Node)