2 from UserDict import DictMixin
3 from hashlib import sha1
5 from django.core.cache import cache
6 from django.core.exceptions import ValidationError
7 from django.core.urlresolvers import NoReverseMatch
8 from django.core.validators import RegexValidator, MinValueValidator
9 from django.db import models
10 from django.forms.models import model_to_dict
12 from philo.models.base import TreeEntity, TreeEntityManager, Entity
13 from philo.models.nodes import Node, TargetURLModel
16 DEFAULT_NAVIGATION_DEPTH = 3
19 class NavigationMapper(object, DictMixin):
21 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`
24 def __init__(self, node):
28 def __getitem__(self, key):
29 return Navigation.objects.get_for_node(self.node, key)
30 #if key not in self._cache:
32 # self._cache[key] = Navigation.objects.get_for_node(self.node, key)
33 # except Navigation.DoesNotExist:
34 # self._cache[key] = None
35 #return self._cache[key]
39 if not hasattr(self, '_navigation'):
40 self._navigation = NavigationMapper(self)
41 return self._navigation
44 Node.navigation = property(navigation)
47 class NavigationManager(models.Manager):
48 use_for_related = True
50 def get_for_node(self, node, key):
51 cache_key = self._get_cache_key(node, key)
52 cached = cache.get(cache_key)
55 opts = Node._mptt_meta
56 left = getattr(node, opts.left_attr)
57 right = getattr(node, opts.right_attr)
58 tree_id = getattr(node, opts.tree_id_attr)
60 "node__%s__lte" % opts.left_attr: left,
61 "node__%s__gte" % opts.right_attr: right,
62 "node__%s" % opts.tree_id_attr: tree_id
64 navs = self.filter(key=key, **kwargs).select_related('node').order_by('-node__%s' % opts.level_attr)
66 roots = nav.roots.all().select_related('target_node')
67 item_opts = NavigationItem._mptt_meta
73 tree_ids.append(getattr(root, item_opts.tree_id_attr))
74 root._cached_children = []
77 '%s__in' % item_opts.tree_id_attr: tree_ids,
78 '%s__lt' % item_opts.level_attr: nav.depth,
79 '%s__gt' % item_opts.level_attr: 0
81 items = NavigationItem.objects.filter(**kwargs).select_related('target_node').order_by('level', 'order')
84 item._cached_children = []
85 parent_pk = getattr(item, '%s_id' % item_opts.parent_attr)
86 item.parent = by_pk[parent_pk]
87 item.parent._cached_children.append(item)
90 cache.set(cache_key, cached)
94 def _get_cache_key(self, node, key):
95 opts = Node._mptt_meta
96 left = getattr(node, opts.left_attr)
97 right = getattr(node, opts.right_attr)
98 tree_id = getattr(node, opts.tree_id_attr)
99 parent_id = getattr(node, "%s_id" % opts.parent_attr)
101 return sha1(unicode(left) + unicode(right) + unicode(tree_id) + unicode(parent_id) + unicode(node.pk) + unicode(key)).hexdigest()
104 class Navigation(Entity):
106 :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.
108 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::
110 >>> node.navigation_set.all()
112 >>> parent = node.parent
113 >>> items = parent.navigation_set.get(key='main').roots.all()
114 >>> parent.navigation["main"] == node.navigation["main"] == list(items)
118 #: A :class:`NavigationManager` instance.
119 objects = NavigationManager()
121 #: 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.
122 node = models.ForeignKey(Node, related_name='navigation_set', help_text="Be available as navigation for this node.")
123 #: 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 }}``.
124 key = models.CharField(max_length=255, validators=[RegexValidator("\w+")], help_text="Must contain one or more alphanumeric characters or underscores.", db_index=True)
125 #: 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.
126 depth = models.PositiveSmallIntegerField(default=DEFAULT_NAVIGATION_DEPTH, validators=[MinValueValidator(1)], help_text="Defines the maximum display depth of this navigation.")
128 def __unicode__(self):
129 return "%s[%s]" % (self.node, self.key)
132 unique_together = ('node', 'key')
135 class NavigationItem(TreeEntity, TargetURLModel):
136 #: 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.
137 navigation = models.ForeignKey(Navigation, blank=True, null=True, related_name='roots', help_text="Be a root in this navigation tree.")
138 #: The text which will be displayed in the navigation. This is a :class:`CharField` instance with max length 50.
139 text = models.CharField(max_length=50)
141 #: The order in which the :class:`NavigationItem` will be displayed.
142 order = models.PositiveSmallIntegerField(default=0)
144 def get_path(self, root=None, pathsep=u' › ', field='text'):
145 return super(NavigationItem, self).get_path(root, pathsep, field)
146 path = property(get_path)
149 super(NavigationItem, self).clean()
150 if bool(self.parent) == bool(self.navigation):
151 raise ValidationError("Exactly one of `parent` and `navigation` must be defined.")
153 def is_active(self, request):
154 """Returns ``True`` if the :class:`NavigationItem` is considered active for a given request and ``False`` otherwise."""
155 if self.target_url == request.path:
156 # Handle the `default` case where the target_url and requested path
160 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):
161 # If there's no target_node, double-check whether it's a full-url
165 if self.target_node and not self.url_or_subpath:
166 # If there is a target node and it's targeted simply, but the target URL is not
167 # the same as the request path, check whether the target node is an ancestor
168 # of the requested node. If so, this is active unless the target node
169 # is the same as the ``host node`` for this navigation structure.
171 host_node = self.get_root().navigation.node
172 except AttributeError:
175 if self.target_node != host_node and self.target_node.is_ancestor_of(request.node):
180 def has_active_descendants(self, request):
181 """Returns ``True`` if the :class:`NavigationItem` has active descendants and ``False`` otherwise."""
182 for child in self.get_children():
183 if child.is_active(request) or child.has_active_descendants(request):