Add dynamic-class trickery to get ListView titles.
authorW. Trevor King <wking@drexel.edu>
Fri, 5 Aug 2011 01:25:39 +0000 (21:25 -0400)
committerW. Trevor King <wking@drexel.edu>
Fri, 5 Aug 2011 01:25:39 +0000 (21:25 -0400)
cookbook/urls.py
cookbook/views.py

index 146dbccaf1404117e7acd5fbf34bec036815895d..2c5bf64456e68f777f2f6a68e39a53e51525056e 100644 (file)
@@ -3,14 +3,17 @@ from django.conf.urls.defaults import patterns, include, url
 from django.views.generic import DetailView, ListView
 import taggit.models
 
-import models
+from . import models
+from . import views
 
 # Uncomment the next two lines to enable the admin:
 from django.contrib import admin
 admin.autodiscover()
 
 urlpatterns = patterns('',
-    url(r'^$', ListView.as_view(
+    url(r'^$', views.static_context_list_view_factory(
+            extra_context={'title': 'Recipes'},
+            ).as_view(
             queryset=models.Recipe.objects.all().order_by('name'),
             context_object_name='recipes',
             template_name='cookbook/recipes.html'),
@@ -18,7 +21,9 @@ urlpatterns = patterns('',
      url(r'^recipe/(?P<pk>\d+)/$', DetailView.as_view(
             model=models.Recipe, template_name='cookbook/recipe.html'),
         name='recipe'),
-     url(r'^tags/$', ListView.as_view(
+     url(r'^tags/$', views.static_context_list_view_factory(
+            extra_context={'title': 'Tags'},
+            ).as_view(
             queryset=taggit.models.Tag.objects.all(),
             context_object_name='tags',
             template_name='cookbook/tags.html'),
index dbc1bd2166c66c416f8a94efc442004bd4050abe..648ec66f2dd1ffa458b3ad8f0263e84d3c2cc6e4 100644 (file)
@@ -1,6 +1,7 @@
 from django.http import HttpResponse
 from django.shortcuts import render_to_response, get_object_or_404
 from django.template import RequestContext
+from django.views.generic import ListView
 
 from taggit.models import Tag
 from .models import Recipe
@@ -12,3 +13,20 @@ def tag(request, pk):
     return render_to_response(
         'cookbook/recipes.html', {'recipes': recipes, 'title': tag.name},
         RequestContext(request))
+
+class StaticContextListView (ListView):
+    _name_counter = 0
+    def get_context_data(self, **kwargs):
+        context = super(StaticContextListView, self).get_context_data(**kwargs)
+        context.update(self._extra_context)
+        return context
+
+def static_context_list_view_factory(extra_context):
+    class_name = 'StaticContextListView_{:d}'.format(
+        StaticContextListView._name_counter)
+    StaticContextListView._name_counter += 1
+    class_bases = (StaticContextListView,)
+    class_dict = dict(StaticContextListView.__dict__)
+    new_class = type(class_name, class_bases, class_dict)
+    new_class._extra_context = extra_context
+    return new_class