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
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 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 raise ViewDoesNotProvideSubpaths
67 def attributes_with_node(self, node):
68 return QuerySetMapper(self.attribute_set, passthrough=node.attributes)
70 def render_to_response(self, request, extra_context=None):
71 if not hasattr(request, 'node'):
72 raise MIDDLEWARE_NOT_CONFIGURED
74 extra_context = extra_context or {}
75 view_about_to_render.send(sender=self, request=request, extra_context=extra_context)
76 response = self.actually_render_to_response(request, extra_context)
77 view_finished_rendering.send(sender=self, response=response)
80 def actually_render_to_response(self, request, extra_context=None):
81 raise NotImplementedError('View subclasses must implement render_to_response.')
87 _view_content_type_limiter.cls = View
90 class MultiView(View):
91 accepts_subpath = True
94 def urlpatterns(self, obj):
95 raise NotImplementedError("MultiView subclasses must implement urlpatterns.")
97 def get_reverse_params(self, obj):
98 """This method should return a view_name, args, kwargs tuple suitable for reversing a url for the given obj using self as the urlconf."""
99 raise NotImplementedError("MultiView subclasses must implement get_subpath.")
101 def actually_render_to_response(self, request, extra_context=None):
103 subpath = request.node.subpath
106 subpath = "/" + subpath
107 view, args, kwargs = resolve(subpath, urlconf=self)
108 view_args = getargspec(view)
109 if extra_context is not None and ('extra_context' in view_args[0] or view_args[2] is not None):
110 if 'extra_context' in kwargs:
111 extra_context.update(kwargs['extra_context'])
112 kwargs['extra_context'] = extra_context
113 return view(request, *args, **kwargs)
119 class Redirect(View):
124 target = models.CharField(max_length=200, validators=[RedirectValidator()])
125 status_code = models.IntegerField(choices=STATUS_CODES, default=302, verbose_name='redirect type')
127 def actually_render_to_response(self, request, extra_context=None):
128 response = HttpResponseRedirect(self.target)
129 response.status_code = self.status_code
136 # Why does this exist?
138 """ For storing arbitrary files """
140 mimetype = models.CharField(max_length=255)
141 file = models.FileField(upload_to='philo/files/%Y/%m/%d')
143 def actually_render_to_response(self, request, extra_context=None):
144 wrapper = FileWrapper(self.file)
145 response = HttpResponse(wrapper, content_type=self.mimetype)
146 response['Content-Length'] = self.file.size
152 def __unicode__(self):
153 return self.file.name
156 register_templatetags('philo.templatetags.nodes')
157 register_value_model(Node)