Initial flexible attributes commit. Removed Relationship model in favor of a flexible...
[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.servers.basehttp import FileWrapper
7 from django.core.urlresolvers import resolve, clear_url_caches
8 from django.template import add_to_builtins as register_templatetags
9 from inspect import getargspec
10 from philo.models.base import TreeEntity, Entity, QuerySetMapper, register_value_model
11 from philo.utils import ContentTypeSubclassLimiter
12 from philo.validators import RedirectValidator
13 from philo.exceptions import ViewDoesNotProvideSubpaths, AncestorDoesNotExist
14 from philo.signals import view_about_to_render, view_finished_rendering
15
16
17 _view_content_type_limiter = ContentTypeSubclassLimiter(None)
18
19
20 class Node(TreeEntity):
21         view_content_type = models.ForeignKey(ContentType, related_name='node_view_set', limit_choices_to=_view_content_type_limiter)
22         view_object_id = models.PositiveIntegerField()
23         view = generic.GenericForeignKey('view_content_type', 'view_object_id')
24         
25         @property
26         def accepts_subpath(self):
27                 if self.view:
28                         return self.view.accepts_subpath
29                 return False
30         
31         def render_to_response(self, request, path=None, subpath=None, extra_context=None):
32                 return self.view.render_to_response(self, request, path, subpath, extra_context)
33         
34         def get_absolute_url(self):
35                 root = Site.objects.get_current().root_node
36                 try:
37                         return '/%s' % self.get_path(root=root)
38                 except AncestorDoesNotExist:
39                         return None
40         
41         class Meta:
42                 app_label = 'philo'
43
44
45 # the following line enables the selection of a node as the root for a given django.contrib.sites Site object
46 models.ForeignKey(Node, related_name='sites', null=True, blank=True).contribute_to_class(Site, 'root_node')
47
48
49 class View(Entity):
50         nodes = generic.GenericRelation(Node, content_type_field='view_content_type', object_id_field='view_object_id')
51         
52         accepts_subpath = False
53         
54         def get_subpath(self, obj):
55                 raise ViewDoesNotProvideSubpaths
56         
57         def attributes_with_node(self, node):
58                 return QuerySetMapper(self.attribute_set, passthrough=node.attributes)
59         
60         def render_to_response(self, node, request, path=None, subpath=None, extra_context=None):
61                 extra_context = extra_context or {}
62                 view_about_to_render.send(sender=self, node=node, request=request, path=path, subpath=subpath, extra_context=extra_context)
63                 response = self.actually_render_to_response(node, request, path, subpath, extra_context)
64                 view_finished_rendering.send(sender=self, response=response)
65                 return response
66         
67         def actually_render_to_response(self, node, request, path=None, subpath=None, extra_context=None):
68                 raise NotImplementedError('View subclasses must implement render_to_response.')
69         
70         class Meta:
71                 abstract = True
72
73
74 _view_content_type_limiter.cls = View
75
76
77 class MultiView(View):
78         accepts_subpath = True
79         
80         urlpatterns = []
81         
82         def actually_render_to_response(self, node, request, path=None, subpath=None, extra_context=None):
83                 clear_url_caches()
84                 if not subpath:
85                         subpath = ""
86                 subpath = "/" + subpath
87                 view, args, kwargs = resolve(subpath, urlconf=self)
88                 view_args = getargspec(view)
89                 if extra_context is not None and ('extra_context' in view_args[0] or view_args[2] is not None):
90                         if 'extra_context' in kwargs:
91                                 extra_context.update(kwargs['extra_context'])
92                         kwargs['extra_context'] = extra_context
93                 if 'node' in view_args[0] or view_args[2] is not None:
94                         kwargs['node'] = node
95                 return view(request, *args, **kwargs)
96         
97         class Meta:
98                 abstract = True
99
100
101 class Redirect(View):
102         STATUS_CODES = (
103                 (302, 'Temporary'),
104                 (301, 'Permanent'),
105         )
106         target = models.CharField(max_length=200, validators=[RedirectValidator()])
107         status_code = models.IntegerField(choices=STATUS_CODES, default=302, verbose_name='redirect type')
108         
109         def actually_render_to_response(self, node, request, path=None, subpath=None, extra_context=None):
110                 response = HttpResponseRedirect(self.target)
111                 response.status_code = self.status_code
112                 return response
113         
114         class Meta:
115                 app_label = 'philo'
116
117
118 class File(View):
119         """ For storing arbitrary files """
120         
121         mimetype = models.CharField(max_length=255)
122         file = models.FileField(upload_to='philo/files/%Y/%m/%d')
123         
124         def actually_render_to_response(self, node, request, path=None, subpath=None, extra_context=None):
125                 wrapper = FileWrapper(self.file)
126                 response = HttpResponse(wrapper, content_type=self.mimetype)
127                 response['Content-Length'] = self.file.size
128                 return response
129         
130         class Meta:
131                 app_label = 'philo'
132         
133         def __unicode__(self):
134                 return self.file.name
135
136
137 register_templatetags('philo.templatetags.nodes')
138 register_value_model(Node)