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.servers.basehttp import FileWrapper
7 from django.core.urlresolvers import resolve, clear_url_caches, reverse, NoReverseMatch
8 from django.template import add_to_builtins as register_templatetags
9 from inspect import getargspec
10 from philo.exceptions import MIDDLEWARE_NOT_CONFIGURED
11 from philo.models.base import TreeEntity, Entity, QuerySetMapper, register_value_model
12 from philo.models.fields import JSONField
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 handles_subpath(self, subpath):
34 return self.view.handles_subpath(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, request=None, with_domain=False, secure=False):
40 return self.construct_url(request=request, with_domain=with_domain, secure=secure)
42 def construct_url(self, subpath="/", request=None, with_domain=False, secure=False):
44 This method will construct a URL based on the Node's location.
45 If a request is passed in, that will be used as a backup in case
46 the Site lookup fails. The Site lookup takes precedence because
47 it's what's used to find the root node. This will raise:
48 - NoReverseMatch if philo-root is not reverseable
49 - Site.DoesNotExist if a domain is requested but not buildable.
50 - AncestorDoesNotExist if the root node of the site isn't an
51 ancestor of this instance.
53 # Try reversing philo-root first, since we can't do anything if that fails.
54 root_url = reverse('philo-root')
57 current_site = Site.objects.get_current()
58 except Site.DoesNotExist:
59 if request is not None:
60 current_site = RequestSite(request)
62 # If they want a domain and we can't figure one out,
63 # best to reraise the error to let them know.
68 root = getattr(current_site, 'root_node', None)
69 path = self.get_path(root=root)
71 if current_site and with_domain:
72 domain = "http%s://%s" % (secure and "s" or "", current_site.domain)
79 return '%s%s%s%s' % (domain, root_url, path, subpath)
85 # the following line enables the selection of a node as the root for a given django.contrib.sites Site object
86 models.ForeignKey(Node, related_name='sites', null=True, blank=True).contribute_to_class(Site, 'root_node')
90 nodes = generic.GenericRelation(Node, content_type_field='view_content_type', object_id_field='view_object_id')
92 accepts_subpath = False
94 def handles_subpath(self, subpath):
95 if not self.accepts_subpath and subpath != "/":
99 def reverse(self, view_name=None, args=None, kwargs=None, node=None, obj=None):
100 """Shortcut method to handle the common pattern of getting the
101 absolute url for a view's subpaths."""
102 if not self.accepts_subpath:
103 raise ViewDoesNotProvideSubpaths
106 # Perhaps just override instead of combining?
107 obj_view_name, obj_args, obj_kwargs = self.get_reverse_params(obj)
108 if view_name is None:
109 view_name = obj_view_name
110 args = list(obj_args) + list(args or [])
111 obj_kwargs.update(kwargs or {})
115 subpath = reverse(view_name, urlconf=self, args=args or [], kwargs=kwargs or {})
116 except NoReverseMatch:
117 raise ViewCanNotProvideSubpath
120 return node.construct_url(subpath)
123 def get_reverse_params(self, obj):
124 """This method should return a view_name, args, kwargs tuple suitable for reversing a url for the given obj using self as the urlconf."""
125 raise NotImplementedError("View subclasses must implement get_reverse_params to support subpaths.")
127 def attributes_with_node(self, node):
128 return QuerySetMapper(self.attribute_set, passthrough=node.attributes)
130 def render_to_response(self, request, extra_context=None):
131 if not hasattr(request, 'node'):
132 raise MIDDLEWARE_NOT_CONFIGURED
134 extra_context = extra_context or {}
135 view_about_to_render.send(sender=self, request=request, extra_context=extra_context)
136 response = self.actually_render_to_response(request, extra_context)
137 view_finished_rendering.send(sender=self, response=response)
140 def actually_render_to_response(self, request, extra_context=None):
141 raise NotImplementedError('View subclasses must implement actually_render_to_response.')
147 _view_content_type_limiter.cls = View
150 class MultiView(View):
151 accepts_subpath = True
154 def urlpatterns(self):
155 raise NotImplementedError("MultiView subclasses must implement urlpatterns.")
157 def handles_subpath(self, subpath):
158 if not super(MultiView, self).handles_subpath(subpath):
161 resolve(subpath, urlconf=self)
166 def actually_render_to_response(self, request, extra_context=None):
168 subpath = request.node.subpath
169 view, args, kwargs = resolve(subpath, urlconf=self)
170 view_args = getargspec(view)
171 if extra_context is not None and ('extra_context' in view_args[0] or view_args[2] is not None):
172 if 'extra_context' in kwargs:
173 extra_context.update(kwargs['extra_context'])
174 kwargs['extra_context'] = extra_context
175 return view(request, *args, **kwargs)
177 def get_context(self):
178 """Hook for providing instance-specific context - such as the value of a Field - to all views."""
181 def basic_view(self, field_name):
183 Given the name of a field on ``self``, accesses the value of
184 that field and treats it as a ``View`` instance. Creates a
185 basic context based on self.get_context() and any extra_context
186 that was passed in, then calls the ``View`` instance's
187 render_to_response() method. This method is meant to be called
188 to return a view function appropriate for urlpatterns.
190 field = self._meta.get_field(field_name)
191 view = getattr(self, field.name, None)
193 def inner(request, extra_context=None, **kwargs):
196 context = self.get_context()
197 context.update(extra_context or {})
198 return view.render_to_response(request, extra_context=context)
206 class TargetURLModel(models.Model):
207 target_node = models.ForeignKey(Node, blank=True, null=True, related_name="%(app_label)s_%(class)s_related")
208 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.")
209 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.")
212 # Should this be enforced? Not enforcing it would allow creation of "headers" in the navbar.
213 if not self.target_node and not self.url_or_subpath:
214 raise ValidationError("Either a target node or a url must be defined.")
216 if self.reversing_parameters and not (self.url_or_subpath or self.target_node):
217 raise ValidationError("Reversing parameters require either a view name or a target node.")
220 self.get_target_url()
221 except NoReverseMatch, e:
222 raise ValidationError(e.message)
224 super(TargetURLModel, self).clean()
226 def get_reverse_params(self):
227 params = self.reversing_parameters
228 args = isinstance(params, list) and params or None
229 kwargs = isinstance(params, dict) and params or None
230 return self.url_or_subpath, args, kwargs
232 def get_target_url(self):
233 node = self.target_node
234 if node is not None and node.accepts_subpath and self.url_or_subpath:
235 if self.reversing_parameters is not None:
236 view_name, args, kwargs = self.get_reversing_params()
237 subpath = node.view.reverse(view_name, args=args, kwargs=kwargs)
239 subpath = self.url_or_subpath
240 if subpath[0] != '/':
241 subpath = '/' + subpath
242 return node.construct_url(subpath)
243 elif node is not None:
244 return node.get_absolute_url()
246 if self.reversing_parameters is not None:
247 view_name, args, kwargs = self.get_reversing_params()
248 return reverse(view_name, args=args, kwargs=kwargs)
249 return self.url_or_subpath
250 target_url = property(get_target_url)
256 class Redirect(View, TargetURLModel):
261 status_code = models.IntegerField(choices=STATUS_CODES, default=302, verbose_name='redirect type')
263 def actually_render_to_response(self, request, extra_context=None):
264 response = HttpResponseRedirect(self.target_url)
265 response.status_code = self.status_code
273 """ For storing arbitrary files """
275 mimetype = models.CharField(max_length=255)
276 file = models.FileField(upload_to='philo/files/%Y/%m/%d')
278 def actually_render_to_response(self, request, extra_context=None):
279 wrapper = FileWrapper(self.file)
280 response = HttpResponse(wrapper, content_type=self.mimetype)
281 response['Content-Length'] = self.file.size
287 def __unicode__(self):
288 return self.file.name
291 register_templatetags('philo.templatetags.nodes')
292 register_value_model(Node)