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 django.utils.encoding import smart_str
11 from inspect import getargspec
12 from philo.exceptions import MIDDLEWARE_NOT_CONFIGURED
13 from philo.models.base import TreeEntity, Entity, QuerySetMapper, register_value_model
14 from philo.models.fields import JSONField
15 from philo.utils import ContentTypeSubclassLimiter
16 from philo.validators import RedirectValidator
17 from philo.exceptions import ViewCanNotProvideSubpath, ViewDoesNotProvideSubpaths, AncestorDoesNotExist
18 from philo.signals import view_about_to_render, view_finished_rendering
21 _view_content_type_limiter = ContentTypeSubclassLimiter(None)
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 handles_subpath(self, subpath):
36 return self.view.handles_subpath(subpath)
38 def render_to_response(self, request, extra_context=None):
39 return self.view.render_to_response(request, extra_context)
41 def get_absolute_url(self, request=None, with_domain=False, secure=False):
42 return self.construct_url(request=request, with_domain=with_domain, secure=secure)
44 def construct_url(self, subpath="/", request=None, with_domain=False, secure=False):
46 This method will construct a URL based on the Node's location.
47 If a request is passed in, that will be used as a backup in case
48 the Site lookup fails. The Site lookup takes precedence because
49 it's what's used to find the root node. This will raise:
50 - NoReverseMatch if philo-root is not reverseable
51 - Site.DoesNotExist if a domain is requested but not buildable.
52 - AncestorDoesNotExist if the root node of the site isn't an
53 ancestor of this instance.
55 # Try reversing philo-root first, since we can't do anything if that fails.
56 root_url = reverse('philo-root')
59 current_site = Site.objects.get_current()
60 except Site.DoesNotExist:
61 if request is not None:
62 current_site = RequestSite(request)
64 # If they want a domain and we can't figure one out,
65 # best to reraise the error to let them know.
70 root = getattr(current_site, 'root_node', None)
71 path = self.get_path(root=root)
73 if current_site and with_domain:
74 domain = "http%s://%s" % (secure and "s" or "", current_site.domain)
78 if not path or subpath == "/":
81 return '%s%s%s%s' % (domain, root_url, path, subpath)
87 # the following line enables the selection of a node as the root for a given django.contrib.sites Site object
88 models.ForeignKey(Node, related_name='sites', null=True, blank=True).contribute_to_class(Site, 'root_node')
92 nodes = generic.GenericRelation(Node, content_type_field='view_content_type', object_id_field='view_object_id')
94 accepts_subpath = False
96 def handles_subpath(self, subpath):
97 if not self.accepts_subpath and subpath != "/":
101 def reverse(self, view_name=None, args=None, kwargs=None, node=None, obj=None):
102 """Shortcut method to handle the common pattern of getting the
103 absolute url for a view's subpaths."""
104 if not self.accepts_subpath:
105 raise ViewDoesNotProvideSubpaths
108 # Perhaps just override instead of combining?
109 obj_view_name, obj_args, obj_kwargs = self.get_reverse_params(obj)
110 if view_name is None:
111 view_name = obj_view_name
112 args = list(obj_args) + list(args or [])
113 obj_kwargs.update(kwargs or {})
117 subpath = reverse(view_name, urlconf=self, args=args or [], kwargs=kwargs or {})
118 except NoReverseMatch, e:
119 raise ViewCanNotProvideSubpath(e.message)
122 return node.construct_url(subpath)
125 def get_reverse_params(self, obj):
126 """This method should return a view_name, args, kwargs tuple suitable for reversing a url for the given obj using self as the urlconf."""
127 raise NotImplementedError("View subclasses must implement get_reverse_params to support subpaths.")
129 def attributes_with_node(self, node):
130 return QuerySetMapper(self.attribute_set, passthrough=node.attributes)
132 def render_to_response(self, request, extra_context=None):
133 if not hasattr(request, 'node'):
134 raise MIDDLEWARE_NOT_CONFIGURED
136 extra_context = extra_context or {}
137 view_about_to_render.send(sender=self, request=request, extra_context=extra_context)
138 response = self.actually_render_to_response(request, extra_context)
139 view_finished_rendering.send(sender=self, response=response)
142 def actually_render_to_response(self, request, extra_context=None):
143 raise NotImplementedError('View subclasses must implement actually_render_to_response.')
149 _view_content_type_limiter.cls = View
152 class MultiView(View):
153 accepts_subpath = True
156 def urlpatterns(self):
157 raise NotImplementedError("MultiView subclasses must implement urlpatterns.")
159 def handles_subpath(self, subpath):
160 if not super(MultiView, self).handles_subpath(subpath):
163 resolve(subpath, urlconf=self)
168 def actually_render_to_response(self, request, extra_context=None):
170 subpath = request.node.subpath
171 view, args, kwargs = resolve(subpath, urlconf=self)
172 view_args = getargspec(view)
173 if extra_context is not None and ('extra_context' in view_args[0] or view_args[2] is not None):
174 if 'extra_context' in kwargs:
175 extra_context.update(kwargs['extra_context'])
176 kwargs['extra_context'] = extra_context
177 return view(request, *args, **kwargs)
179 def get_context(self):
180 """Hook for providing instance-specific context - such as the value of a Field - to all views."""
183 def basic_view(self, field_name):
185 Given the name of a field on ``self``, accesses the value of
186 that field and treats it as a ``View`` instance. Creates a
187 basic context based on self.get_context() and any extra_context
188 that was passed in, then calls the ``View`` instance's
189 render_to_response() method. This method is meant to be called
190 to return a view function appropriate for urlpatterns.
192 field = self._meta.get_field(field_name)
193 view = getattr(self, field.name, None)
195 def inner(request, extra_context=None, **kwargs):
198 context = self.get_context()
199 context.update(extra_context or {})
200 return view.render_to_response(request, extra_context=context)
208 class TargetURLModel(models.Model):
209 target_node = models.ForeignKey(Node, blank=True, null=True, related_name="%(app_label)s_%(class)s_related")
210 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.")
211 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.")
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, ViewCanNotProvideSubpath), e:
223 raise ValidationError(e.message)
225 super(TargetURLModel, self).clean()
227 def get_reverse_params(self):
228 params = self.reversing_parameters
230 if isinstance(params, list):
232 elif isinstance(params, dict):
233 # Convert unicode keys to strings for Python < 2.6.5. Compare
234 # http://stackoverflow.com/questions/4598604/how-to-pass-unicode-keywords-to-kwargs
235 kwargs = dict([(smart_str(k, 'ascii'), v) for k, v in params.items()])
236 return self.url_or_subpath, args, kwargs
238 def get_target_url(self):
239 node = self.target_node
240 if node is not None and node.accepts_subpath and self.url_or_subpath:
241 if self.reversing_parameters is not None:
242 view_name, args, kwargs = self.get_reverse_params()
243 subpath = node.view.reverse(view_name, args=args, kwargs=kwargs)
245 subpath = self.url_or_subpath
246 if subpath[0] != '/':
247 subpath = '/' + subpath
248 return node.construct_url(subpath)
249 elif node is not None:
250 return node.get_absolute_url()
252 if self.reversing_parameters is not None:
253 view_name, args, kwargs = self.get_reverse_params()
254 return reverse(view_name, args=args, kwargs=kwargs)
255 return self.url_or_subpath
256 target_url = property(get_target_url)
262 class Redirect(TargetURLModel, View):
267 status_code = models.IntegerField(choices=STATUS_CODES, default=302, verbose_name='redirect type')
269 def actually_render_to_response(self, request, extra_context=None):
270 response = HttpResponseRedirect(self.target_url)
271 response.status_code = self.status_code
279 """ For storing arbitrary files """
281 mimetype = models.CharField(max_length=255)
282 file = models.FileField(upload_to='philo/files/%Y/%m/%d')
284 def actually_render_to_response(self, request, extra_context=None):
285 wrapper = FileWrapper(self.file)
286 response = HttpResponse(wrapper, content_type=self.mimetype)
287 response['Content-Length'] = self.file.size
293 def __unicode__(self):
294 return self.file.name
297 register_templatetags('philo.templatetags.nodes')
298 register_value_model(Node)