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)
126 class Redirect(View):
131 target = models.CharField(max_length=200, validators=[RedirectValidator()])
132 status_code = models.IntegerField(choices=STATUS_CODES, default=302, verbose_name='redirect type')
134 def actually_render_to_response(self, request, extra_context=None):
135 response = HttpResponseRedirect(self.target)
136 response.status_code = self.status_code
143 # Why does this exist?
145 """ For storing arbitrary files """
147 mimetype = models.CharField(max_length=255)
148 file = models.FileField(upload_to='philo/files/%Y/%m/%d')
150 def actually_render_to_response(self, request, extra_context=None):
151 wrapper = FileWrapper(self.file)
152 response = HttpResponse(wrapper, content_type=self.mimetype)
153 response['Content-Length'] = self.file.size
159 def __unicode__(self):
160 return self.file.name
163 register_templatetags('philo.templatetags.nodes')
164 register_value_model(Node)