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