Minor correction to embed template tag: updating the context adds an additional conte...
[philo.git] / models / nodes.py
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
17
18
19 _view_content_type_limiter = ContentTypeSubclassLimiter(None)
20
21
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')
26         
27         @property
28         def accepts_subpath(self):
29                 if self.view:
30                         return self.view.accepts_subpath
31                 return False
32         
33         def render_to_response(self, request, extra_context=None):
34                 return self.view.render_to_response(request, extra_context)
35         
36         def get_absolute_url(self):
37                 try:
38                         root = Site.objects.get_current().root_node
39                 except Site.DoesNotExist:
40                         root = None
41                 
42                 try:
43                         path = self.get_path(root=root)
44                         if path:
45                                 path += '/'
46                         root_url = reverse('philo-root')
47                         return '%s%s' % (root_url, path)
48                 except AncestorDoesNotExist, ViewDoesNotExist:
49                         return None
50         
51         class Meta:
52                 app_label = 'philo'
53
54
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')
57
58
59 class View(Entity):
60         nodes = generic.GenericRelation(Node, content_type_field='view_content_type', object_id_field='view_object_id')
61         
62         accepts_subpath = False
63         
64         def get_subpath(self, obj):
65                 if not self.accepts_subpath:
66                         raise ViewDoesNotProvideSubpaths
67                 
68                 view_name, args, kwargs = self.get_reverse_params(obj)
69                 try:
70                         return reverse(view_name, args=args, kwargs=kwargs, urlconf=self)
71                 except NoReverseMatch:
72                         raise ViewCanNotProvideSubpath
73         
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.")
77         
78         def attributes_with_node(self, node):
79                 return QuerySetMapper(self.attribute_set, passthrough=node.attributes)
80         
81         def render_to_response(self, request, extra_context=None):
82                 if not hasattr(request, 'node'):
83                         raise MIDDLEWARE_NOT_CONFIGURED
84                 
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)
89                 return response
90         
91         def actually_render_to_response(self, request, extra_context=None):
92                 raise NotImplementedError('View subclasses must implement render_to_response.')
93         
94         class Meta:
95                 abstract = True
96
97
98 _view_content_type_limiter.cls = View
99
100
101 class MultiView(View):
102         accepts_subpath = True
103         
104         @property
105         def urlpatterns(self, obj):
106                 raise NotImplementedError("MultiView subclasses must implement urlpatterns.")
107         
108         def actually_render_to_response(self, request, extra_context=None):
109                 clear_url_caches()
110                 subpath = request.node.subpath
111                 if not subpath:
112                         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)
121         
122         class Meta:
123                 abstract = True
124
125
126 class Redirect(View):
127         STATUS_CODES = (
128                 (302, 'Temporary'),
129                 (301, 'Permanent'),
130         )
131         target = models.CharField(max_length=200, validators=[RedirectValidator()])
132         status_code = models.IntegerField(choices=STATUS_CODES, default=302, verbose_name='redirect type')
133         
134         def actually_render_to_response(self, request, extra_context=None):
135                 response = HttpResponseRedirect(self.target)
136                 response.status_code = self.status_code
137                 return response
138         
139         class Meta:
140                 app_label = 'philo'
141
142
143 # Why does this exist?
144 class File(View):
145         """ For storing arbitrary files """
146         
147         mimetype = models.CharField(max_length=255)
148         file = models.FileField(upload_to='philo/files/%Y/%m/%d')
149         
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
154                 return response
155         
156         class Meta:
157                 app_label = 'philo'
158         
159         def __unicode__(self):
160                 return self.file.name
161
162
163 register_templatetags('philo.templatetags.nodes')
164 register_value_model(Node)