Corrections to has_navigation and navigation_host to use the new NavigationMapper...
[philo.git] / philo / contrib / shipherd / models.py
1 #encoding: utf-8
2 from UserDict import DictMixin
3
4 from django.core.exceptions import ValidationError
5 from django.core.urlresolvers import NoReverseMatch
6 from django.core.validators import RegexValidator, MinValueValidator
7 from django.db import models
8 from django.forms.models import model_to_dict
9
10 from philo.models.base import TreeEntity, TreeEntityManager, Entity
11 from philo.models.nodes import Node, TargetURLModel
12
13
14 DEFAULT_NAVIGATION_DEPTH = 3
15
16
17 class NavigationMapper(object, DictMixin):
18         """
19         The :class:`NavigationMapper` is a dictionary-like object which allows easy fetching of the root items of a navigation for a node according to a key. A :class:`NavigationMapper` instance will be available on each node instance as :attr:`Node.navigation` if :mod:`~philo.contrib.shipherd` is in the :setting:`INSTALLED_APPS`
20         
21         """
22         def __init__(self, node):
23                 self.node = node
24                 self._cache = {}
25         
26         def __getitem__(self, key):
27                 if key not in self._cache:
28                         try:
29                                 self._cache[key] = Navigation.objects.get_for_node(self.node, key)
30                         except Navigation.DoesNotExist:
31                                 self._cache[key] = None
32                 return self._cache[key]
33
34
35 def navigation(self):
36         if not hasattr(self, '_navigation'):
37                 self._navigation = NavigationMapper(self)
38         return self._navigation
39
40
41 Node.navigation = property(navigation)
42
43
44 class NavigationManager(models.Manager):
45         use_for_related = True
46         
47         def get_for_node(self, node, key):
48                 opts = Node._mptt_meta
49                 left = getattr(node, opts.left_attr)
50                 right = getattr(node, opts.right_attr)
51                 tree_id = getattr(node, opts.tree_id_attr)
52                 kwargs = {
53                         "node__%s__lte" % opts.left_attr: left,
54                         "node__%s__gte" % opts.right_attr: right,
55                         "node__%s" % opts.tree_id_attr: tree_id
56                 }
57                 navs = self.filter(key=key, **kwargs).select_related('node').order_by('-node__%s' % opts.level_attr)
58                 nav = navs[0]
59                 roots = nav.roots.all().select_related('target_node')
60                 item_opts = NavigationItem._mptt_meta
61                 by_pk = {}
62                 tree_ids = []
63                 
64                 for root in roots:
65                         by_pk[root.pk] = root
66                         tree_ids.append(getattr(root, item_opts.tree_id_attr))
67                         root._cached_children = []
68                 
69                 kwargs = {
70                         '%s__in' % item_opts.tree_id_attr: tree_ids,
71                         '%s__lt' % item_opts.level_attr: nav.depth,
72                         '%s__gt' % item_opts.level_attr: 0
73                 }
74                 items = NavigationItem.objects.filter(**kwargs).select_related('target_node').order_by('level', 'order')
75                 for item in items:
76                         by_pk[item.pk] = item
77                         item._cached_children = []
78                         parent_pk = getattr(item, '%s_id' % item_opts.parent_attr)
79                         item.parent = by_pk[parent_pk]
80                         item.parent._cached_children.append(item)
81                 
82                 return roots
83
84
85 class Navigation(Entity):
86         """
87         :class:`Navigation` represents a group of :class:`NavigationItem`\ s that have an intrinsic relationship in terms of navigating a website. For example, a ``main`` navigation versus a ``side`` navigation, or a ``authenticated`` navigation versus an ``anonymous`` navigation.
88         
89         A :class:`Navigation`'s :class:`NavigationItem`\ s will be accessible from its related :class:`.Node` and that :class:`.Node`'s descendants through a :class:`NavigationMapper` instance at :attr:`Node.navigation`. Example::
90         
91                 >>> node.navigation_set.all()
92                 []
93                 >>> parent = node.parent
94                 >>> items = parent.navigation_set.get(key='main').roots.all()
95                 >>> parent.navigation["main"] == node.navigation["main"] == list(items)
96                 True
97         
98         """
99         #: A :class:`NavigationManager` instance.
100         objects = NavigationManager()
101         
102         #: The :class:`.Node` which the :class:`Navigation` is attached to. The :class:`Navigation` will also be available to all the :class:`.Node`'s descendants and will override any :class:`Navigation` with the same key on any of the :class:`.Node`'s ancestors.
103         node = models.ForeignKey(Node, related_name='navigation_set', help_text="Be available as navigation for this node.")
104         #: Each :class:`Navigation` has a ``key`` which consists of one or more word characters so that it can easily be accessed in a template as ``{{ node.navigation.this_key }}``.
105         key = models.CharField(max_length=255, validators=[RegexValidator("\w+")], help_text="Must contain one or more alphanumeric characters or underscores.", db_index=True)
106         #: There is no limit to the depth of a tree of :class:`NavigationItem`\ s, but ``depth`` will limit how much of the tree will be displayed.
107         depth = models.PositiveSmallIntegerField(default=DEFAULT_NAVIGATION_DEPTH, validators=[MinValueValidator(1)], help_text="Defines the maximum display depth of this navigation.")
108         
109         def __unicode__(self):
110                 return "%s[%s]" % (self.node, self.key)
111         
112         class Meta:
113                 unique_together = ('node', 'key')
114
115
116 class NavigationItem(TreeEntity, TargetURLModel):
117         #: A :class:`ForeignKey` to a :class:`Navigation` instance. If this is not null, then the :class:`NavigationItem` will be a root node of the :class:`Navigation` instance.
118         navigation = models.ForeignKey(Navigation, blank=True, null=True, related_name='roots', help_text="Be a root in this navigation tree.")
119         #: The text which will be displayed in the navigation. This is a :class:`CharField` instance with max length 50.
120         text = models.CharField(max_length=50)
121         
122         #: The order in which the :class:`NavigationItem` will be displayed.
123         order = models.PositiveSmallIntegerField(default=0)
124         
125         def get_path(self, root=None, pathsep=u' › ', field='text'):
126                 return super(NavigationItem, self).get_path(root, pathsep, field)
127         path = property(get_path)
128         
129         def clean(self):
130                 super(NavigationItem, self).clean()
131                 if bool(self.parent) == bool(self.navigation):
132                         raise ValidationError("Exactly one of `parent` and `navigation` must be defined.")
133         
134         def is_active(self, request):
135                 """Returns ``True`` if the :class:`NavigationItem` is considered active for a given request and ``False`` otherwise."""
136                 if self.target_url == request.path:
137                         # Handle the `default` case where the target_url and requested path
138                         # are identical.
139                         return True
140                 
141                 if self.target_node is None and self.url_or_subpath == "http%s://%s%s" % (request.is_secure() and 's' or '', request.get_host(), request.path):
142                         # If there's no target_node, double-check whether it's a full-url
143                         # match.
144                         return True
145                 
146                 if self.target_node and not self.url_or_subpath:
147                         # If there is a target node and it's targeted simply, but the target URL is not
148                         # the same as the request path, check whether the target node is an ancestor
149                         # of the requested node. If so, this is active unless the target node
150                         # is the same as the ``host node`` for this navigation structure.
151                         try:
152                                 host_node = self.get_root().navigation.node
153                         except AttributeError:
154                                 pass
155                         else:
156                                 if self.target_node != host_node and self.target_node.is_ancestor_of(request.node):
157                                         return True
158                 
159                 return False
160         
161         def has_active_descendants(self, request):
162                 """Returns ``True`` if the :class:`NavigationItem` has active descendants and ``False`` otherwise."""
163                 for child in self.get_children():
164                         if child.is_active(request) or child.has_active_descendants(request):
165                                 return True
166                 return False