Merge branch 'master' into navigation
authorStephen Burrows <stephen.r.burrows@gmail.com>
Thu, 23 Dec 2010 17:08:34 +0000 (12:08 -0500)
committerStephen Burrows <stephen.r.burrows@gmail.com>
Thu, 23 Dec 2010 17:08:34 +0000 (12:08 -0500)
contrib/navigation/__init__.py [new file with mode: 0644]
contrib/navigation/admin.py [new file with mode: 0644]
contrib/navigation/migrations/0001_initial.py [new file with mode: 0644]
contrib/navigation/migrations/0002_auto__chg_field_navigation_text.py [new file with mode: 0644]
contrib/navigation/migrations/__init__.py [new file with mode: 0644]
contrib/navigation/models.py [new file with mode: 0644]
contrib/navigation/templatetags/__init__.py [new file with mode: 0644]
contrib/navigation/templatetags/navigation.py [new file with mode: 0644]

diff --git a/contrib/navigation/__init__.py b/contrib/navigation/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/contrib/navigation/admin.py b/contrib/navigation/admin.py
new file mode 100644 (file)
index 0000000..ec073c6
--- /dev/null
@@ -0,0 +1,66 @@
+from django.contrib import admin
+from philo.admin import TreeEntityAdmin, COLLAPSE_CLASSES, NodeAdmin
+from philo.contrib.navigation.models import Navigation
+
+
+NAVIGATION_RAW_ID_FIELDS = ('hosting_node', 'parent', 'target_node')
+
+
+class NavigationInline(admin.StackedInline):
+       fieldsets = (
+               (None, {
+                       'fields': ('text',)
+               }),
+               ('Target', {
+                       'fields': ('target_node', 'url_or_subpath',)
+               }),
+               ('Advanced', {
+                       'fields': ('reversing_parameters', 'order', 'depth'),
+                       'classes': COLLAPSE_CLASSES
+               }),
+               ('Expert', {
+                       'fields': ('hosting_node', 'parent'),
+                       'classes': COLLAPSE_CLASSES
+               })
+       )
+       raw_id_fields = NAVIGATION_RAW_ID_FIELDS
+       model = Navigation
+       extra = 1
+       sortable_field_name = 'order'
+
+
+class NavigationNavigationInline(NavigationInline):
+       verbose_name = "child"
+       verbose_name_plural = "children"
+
+
+class NodeNavigationInline(NavigationInline):
+       verbose_name_plural = 'navigation'
+
+
+class NavigationAdmin(TreeEntityAdmin):
+       list_display = ('__unicode__', 'target_node', 'url_or_subpath', 'reversing_parameters')
+       fieldsets = (
+               (None, {
+                       'fields': ('text', 'hosting_node',)
+               }),
+               ('Target', {
+                       'fields': ('target_node', 'url_or_subpath',)
+               }),
+               ('Advanced', {
+                       'fields': ('reversing_parameters', 'depth'),
+                       'classes': COLLAPSE_CLASSES
+               }),
+               ('Expert', {
+                       'fields': ('parent', 'order'),
+                       'classes': COLLAPSE_CLASSES
+               })
+       )
+       raw_id_fields = NAVIGATION_RAW_ID_FIELDS
+       inlines = [NavigationNavigationInline] + TreeEntityAdmin.inlines
+
+
+NodeAdmin.inlines = [NodeNavigationInline] + NodeAdmin.inlines
+
+
+admin.site.register(Navigation, NavigationAdmin)
\ No newline at end of file
diff --git a/contrib/navigation/migrations/0001_initial.py b/contrib/navigation/migrations/0001_initial.py
new file mode 100644 (file)
index 0000000..d60c123
--- /dev/null
@@ -0,0 +1,85 @@
+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        
+        # Adding model 'Navigation'
+        db.create_table('navigation_navigation', (
+            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+            ('parent', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='children', null=True, to=orm['navigation.Navigation'])),
+            ('slug', self.gf('django.db.models.fields.SlugField')(max_length=255, db_index=True)),
+            ('lft', self.gf('django.db.models.fields.PositiveIntegerField')(db_index=True)),
+            ('rght', self.gf('django.db.models.fields.PositiveIntegerField')(db_index=True)),
+            ('tree_id', self.gf('django.db.models.fields.PositiveIntegerField')(db_index=True)),
+            ('level', self.gf('django.db.models.fields.PositiveIntegerField')(db_index=True)),
+            ('hosting_node', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='hosted_navigation_set', null=True, to=orm['philo.Node'])),
+            ('target_node', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='targeting_navigation_set', null=True, to=orm['philo.Node'])),
+            ('url_or_subpath', self.gf('django.db.models.fields.CharField')(max_length=200, blank=True)),
+            ('reversing_parameters', self.gf('philo.models.fields.JSONField')(blank=True)),
+            ('text', self.gf('django.db.models.fields.CharField')(max_length=50, blank=True)),
+            ('order', self.gf('django.db.models.fields.PositiveSmallIntegerField')(null=True, blank=True)),
+            ('depth', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=3, null=True, blank=True)),
+        ))
+        db.send_create_signal('navigation', ['Navigation'])
+
+
+    def backwards(self, orm):
+        
+        # Deleting model 'Navigation'
+        db.delete_table('navigation_navigation')
+
+
+    models = {
+        'contenttypes.contenttype': {
+            'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+        },
+        'navigation.navigation': {
+            'Meta': {'object_name': 'Navigation'},
+            'depth': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '3', 'null': 'True', 'blank': 'True'}),
+            'hosting_node': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'hosted_navigation_set'", 'null': 'True', 'to': "orm['philo.Node']"}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'order': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
+            'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['navigation.Navigation']"}),
+            'reversing_parameters': ('philo.models.fields.JSONField', [], {'blank': 'True'}),
+            'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255', 'db_index': 'True'}),
+            'target_node': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'targeting_navigation_set'", 'null': 'True', 'to': "orm['philo.Node']"}),
+            'text': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
+            'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'url_or_subpath': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'})
+        },
+        'philo.attribute': {
+            'Meta': {'unique_together': "(('key', 'entity_content_type', 'entity_object_id'), ('value_content_type', 'value_object_id'))", 'object_name': 'Attribute'},
+            'entity_content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'attribute_entity_set'", 'to': "orm['contenttypes.ContentType']"}),
+            'entity_object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'key': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+            'value_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'attribute_value_set'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
+            'value_object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'})
+        },
+        'philo.node': {
+            'Meta': {'object_name': 'Node'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['philo.Node']"}),
+            'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255', 'db_index': 'True'}),
+            'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'view_content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'node_view_set'", 'to': "orm['contenttypes.ContentType']"}),
+            'view_object_id': ('django.db.models.fields.PositiveIntegerField', [], {})
+        }
+    }
+
+    complete_apps = ['navigation']
diff --git a/contrib/navigation/migrations/0002_auto__chg_field_navigation_text.py b/contrib/navigation/migrations/0002_auto__chg_field_navigation_text.py
new file mode 100644 (file)
index 0000000..c7f4189
--- /dev/null
@@ -0,0 +1,69 @@
+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        
+        # Changing field 'Navigation.text'
+        db.alter_column('navigation_navigation', 'text', self.gf('django.db.models.fields.CharField')(max_length=50))
+
+
+    def backwards(self, orm):
+        
+        # Changing field 'Navigation.text'
+        db.alter_column('navigation_navigation', 'text', self.gf('django.db.models.fields.CharField')(max_length=50, blank=True))
+
+
+    models = {
+        'contenttypes.contenttype': {
+            'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+        },
+        'navigation.navigation': {
+            'Meta': {'object_name': 'Navigation'},
+            'depth': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '3', 'null': 'True', 'blank': 'True'}),
+            'hosting_node': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'hosted_navigation_set'", 'null': 'True', 'to': "orm['philo.Node']"}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'order': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
+            'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['navigation.Navigation']"}),
+            'reversing_parameters': ('philo.models.fields.JSONField', [], {'blank': 'True'}),
+            'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255', 'db_index': 'True'}),
+            'target_node': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'targeting_navigation_set'", 'null': 'True', 'to': "orm['philo.Node']"}),
+            'text': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
+            'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'url_or_subpath': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'})
+        },
+        'philo.attribute': {
+            'Meta': {'unique_together': "(('key', 'entity_content_type', 'entity_object_id'), ('value_content_type', 'value_object_id'))", 'object_name': 'Attribute'},
+            'entity_content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'attribute_entity_set'", 'to': "orm['contenttypes.ContentType']"}),
+            'entity_object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'key': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+            'value_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'attribute_value_set'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
+            'value_object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'})
+        },
+        'philo.node': {
+            'Meta': {'object_name': 'Node'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['philo.Node']"}),
+            'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255', 'db_index': 'True'}),
+            'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'view_content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'node_view_set'", 'to': "orm['contenttypes.ContentType']"}),
+            'view_object_id': ('django.db.models.fields.PositiveIntegerField', [], {})
+        }
+    }
+
+    complete_apps = ['navigation']
diff --git a/contrib/navigation/migrations/__init__.py b/contrib/navigation/migrations/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/contrib/navigation/models.py b/contrib/navigation/models.py
new file mode 100644 (file)
index 0000000..40f8c07
--- /dev/null
@@ -0,0 +1,159 @@
+#encoding: utf-8
+from django.core.exceptions import ValidationError
+from django.core.urlresolvers import NoReverseMatch
+from django.db import models
+from philo.models import TreeEntity, JSONField, Node, TreeManager
+from philo.validators import RedirectValidator
+
+#from mptt.templatetags.mptt_tags import cache_tree_children
+
+
+DEFAULT_NAVIGATION_DEPTH = 3
+
+
+class NavigationManager(TreeManager):
+       
+       # Analagous to contenttypes, cache Navigation to avoid repeated lookups all over the place.
+       # Navigation will probably be used frequently.
+       _cache = {}
+       
+       def for_node(self, node):
+               """
+               Returns the set of Navigation objects for a given node's navigation. This
+               will be the most recent set of defined hosted navigation among the node's
+               ancestors. Lookups are cached so that subsequent lookups for the same node
+               don't hit the database.
+               
+               TODO: Should this create the auto-generated navigation in "physical" form?
+               """
+               try:
+                       return self._get_from_cache(self.db, node)
+               except KeyError:
+                       # Find the most recent host!
+                       ancestors = node.get_ancestors(ascending=True, include_self=True).annotate(num_navigation=models.Count("hosted_navigation"))
+                       
+                       # Iterate down the ancestors until you find one that:
+                       # a) is cached, or
+                       # b) has hosted navigation.
+                       nodes_to_cache = []
+                       host_node = None
+                       for ancestor in ancestors:
+                               if self._is_cached(self.db, ancestor) or ancestor.num_navigation > 0:
+                                       host_node = ancestor
+                                       break
+                               else:
+                                       nodes_to_cache.append(ancestor)
+                       
+                       if not self._is_cached(self.db, host_node):
+                               self._add_to_cache(self.db, host_node)
+                       
+                       # Cache the queryset instance for every node that was passed over, as well.
+                       hosted_navigation = self._get_from_cache(self.db, host_node)
+                       for node in nodes_to_cache:
+                               self._add_to_cache(self.db, node, hosted_navigation)
+               
+               return hosted_navigation
+       
+       def _add_to_cache(self, using, node, qs=None):
+               if node is None or node.pk is None:
+                       qs = self.none()
+                       key = None
+               else:
+                       key = node.pk
+               
+               if qs is None:
+                       qs = node.hosted_navigation.select_related('target_node')
+               
+               self.__class__._cache.setdefault(using, {})[key] = qs
+       
+       def _get_from_cache(self, using, node):
+               key = node.pk
+               return self.__class__._cache[self.db][key]
+       
+       def _is_cached(self, using, node):
+               try:
+                       self._get_from_cache(using, node)
+               except KeyError:
+                       return False
+               return True
+       
+       def clear_cache(self, navigation=None):
+               """
+               Clear out the navigation cache. This needs to happen during database flushes
+               or if a navigation entry is changed to prevent caching of outdated navigation information.
+               
+               TODO: call this method from update() and delete()!
+               """
+               if navigation is None:
+                       self.__class__._cache.clear()
+               else:
+                       cache = self.__class__._cache[self.db]
+                       for pk in cache.keys():
+                               for qs in cache[pk]:
+                                       if navigation in qs:
+                                               cache.pop(pk)
+                                               break
+                                       else:
+                                               for instance in qs:
+                                                       if navigation.is_descendant(instance):
+                                                               cache.pop(pk)
+                                                               break
+                                               # necessary?
+                                               if pk not in cache:
+                                                       break
+
+
+class Navigation(TreeEntity):
+       objects = NavigationManager()
+       text = models.CharField(max_length=50)
+       
+       hosting_node = models.ForeignKey(Node, blank=True, null=True, related_name='hosted_navigation', help_text="Be part of this node's root navigation.")
+       
+       target_node = models.ForeignKey(Node, blank=True, null=True, related_name='targeting_navigation', help_text="Point to this node's url.")
+       url_or_subpath = models.CharField(max_length=200, validators=[RedirectValidator()], blank=True, help_text="Point to this url or, if a node is defined and accepts subpaths, this subpath of the node.")
+       reversing_parameters = JSONField(blank=True, help_text="If reversing parameters are defined, url_or_subpath will instead be interpreted as the view name to be reversed.")
+       
+       order = models.PositiveSmallIntegerField(blank=True, null=True)
+       depth = models.PositiveSmallIntegerField(blank=True, null=True, default=DEFAULT_NAVIGATION_DEPTH, help_text="For the root of a hosted tree, defines the depth of the tree. A blank depth will hide this section of navigation. Otherwise, depth is ignored.")
+       
+       def clean(self):
+               # Should this be enforced? Not enforcing it would allow creation of "headers" in the navbar.
+               if not self.target_node and not self.url_or_subpath:
+                       raise ValidationError("Either a target node or a url must be defined.")
+               
+               if self.reversing_parameters and (not self.url_or_subpath or not self.target_node):
+                       raise ValidationError("Reversing parameters require a view name and a target node.")
+               
+               try:
+                       self.get_target_url()
+               except NoReverseMatch, e:
+                       raise ValidationError(e.message)
+       
+       def get_target_url(self):
+               node = self.target_node
+               if node is not None and node.accepts_subpath and self.url_or_subpath:
+                       if self.reversing_parameters is not None:
+                               view_name = self.url_or_subpath
+                               params = self.reversing_parameters
+                               args = isinstance(params, list) and params or None
+                               kwargs = isinstance(params, dict) and params or None
+                               return node.view.reverse(view_name, args=args, kwargs=kwargs, node=node)
+                       else:
+                               subpath = self.url_or_subpath
+                               while subpath and subpath[0] == '/':
+                                       subpath = subpath[1:]
+                               return '%s%s' % (node.get_absolute_url(), subpath)
+               elif node is not None:
+                       return node.get_absolute_url()
+               else:
+                       return self.url_or_subpath
+       target_url = property(get_target_url)
+       
+       def __unicode__(self):
+               return self.get_path(field='text', pathsep=u' › ')
+       
+       # TODO: Add delete and save methods to handle cache clearing.
+       
+       class Meta:
+               ordering = ['order']
+               verbose_name_plural = 'navigation'
\ No newline at end of file
diff --git a/contrib/navigation/templatetags/__init__.py b/contrib/navigation/templatetags/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/contrib/navigation/templatetags/navigation.py b/contrib/navigation/templatetags/navigation.py
new file mode 100644 (file)
index 0000000..c74891b
--- /dev/null
@@ -0,0 +1,37 @@
+from django import template
+from django.conf import settings
+from philo.contrib.navigation.models import Navigation
+
+
+register = template.Library()
+
+
+@register.filter
+def get_navigation(node):
+       roots = Navigation.objects.for_node(node)
+       qs = None
+       for root in roots:
+               root_qs = root.get_descendants(include_self=True).complex_filter({'%s__lte' % root._mptt_meta.level_attr: root.get_level() + root.depth}).exclude(depth__isnull=True)
+               if qs is None:
+                       qs = root_qs
+               else:
+                       qs |= root_qs
+       return qs
+
+@register.filter
+def is_active(navigation, request):
+       """
+       Returns true if the navigation is considered `active`.
+       
+       But what does "active" mean? Should this be defined on the model instead, perhaps?
+       """
+       try:
+               if navigation.target_node == request.node:
+                       if request.path == navigation.target_url:
+                               return True
+                       return False
+               if navigation.target_url in request.path:
+                       return True
+       except:
+               pass
+       return False
\ No newline at end of file