March 27th, 2012

Django 1.3 Generic views and extra_context

Tutorial for: Django

A very short tutorial about how to easily implement an 'extra_context' variable for your generic views in Django 1.3 and higher.

Starting with Django 1.3, the generic view functions are no more. With Django 1.4, they are no longer supported at all. Do you heavily depend on adding various extra_context's to your generic views? This isn't a problem, if you have many generic views which share the same extra_context. However, sometimes you may attach a specific form to a generic view, a form to add additional items. This would require one to subclass the generic class for each of these specific forms, what a pain for a class which will only be used once! You could put it into your default context via a context_processor, but then this will overload your context with variables you only use once or twice. Here is a solution which implements the old style extra_context in class-based generic views for your existing and future projects:

from django.views.generic.list import ListView

class ContextListView(ListView):
	extra_context = {}
	def get_context_data(self, **kwargs):
		context = super(ContextListView, self).get_context_data(**kwargs)
		context.update(self.extra_context)
		return context

This will make a new variable to use when using the generic view in your urls.py. Here is an example on how you would use it:

url_patterns = patterns('',
	url(r'^$', ContextListView.as_view(queryset=Book.objects.filter(public=True),extra_context={'form':NewBookForm()}), name='book-list'),
)

There you have it. Not sure why Django doesn't do this by default. It boggles me. It still allows customization of the context, but allows migrating from older code much easier.

Feb. 2, 2013, 7:04 p.m. - Ben Healey

Thanks for this. I've been trying to implement extra_context so I can pass in some stuff for conditional processing in my views - this approach did the trick nicely.

April 20, 2013, 4:06 a.m. - Farhan Ahmad

Thanks for sharing!

Python Powered | © 2012-2014 Kevin Veroneau