From 853a69de2ab081cb05440be410f747d47f8be73d Mon Sep 17 00:00:00 2001 From: "W. Trevor King" Date: Thu, 4 Aug 2011 21:25:39 -0400 Subject: [PATCH] Add dynamic-class trickery to get ListView titles. --- cookbook/urls.py | 11 ++++++++--- cookbook/views.py | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/cookbook/urls.py b/cookbook/urls.py index 146dbcc..2c5bf64 100644 --- a/cookbook/urls.py +++ b/cookbook/urls.py @@ -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\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'), diff --git a/cookbook/views.py b/cookbook/views.py index dbc1bd2..648ec66 100644 --- a/cookbook/views.py +++ b/cookbook/views.py @@ -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 -- 2.26.2