There’s no question that using generic views can speed up development substantially. In most projects, however, there comes a moment when the generic views no longer suffice. Indeed, the most common question asked by new Django developers is how to make generic views handle a wider array of situations. Luckily, in nearly every one of these cases, there are ways to simply extend generic views to handle a larger array of use cases. These situations usually fall into a handful of patterns dealt with in the sections that follow.
Making “Friendly” Template Contexts – You might have noticed that sample publisher list template stores all the books in a variable named object_list. While this works just fine, it isn’t all that “friendly” to template authors: they have to “just know” that they’re dealing with books here. A better name for that variable would be publisher_list; that variable’s content is pretty obvious. We can change the name of that variable easily with the template_object_name argument:
publisher_info = {
“queryset” : Publisher.objects.all(),
“template_object_name” : “publisher”,
}
urlpatterns = patterns(”,
(r’^publishers/$’, list_detail.object_list, publisher_info)
)
Providing a useful template_object_name is always a good idea. Your coworkers who design templates will thank you.
Adding Extra Context – Often you simply need to present some extra information beyond that provided by the generic view. For example, think of showing a list of all the other publishers on each publisher detail page. The object_detail generic view provides the publisher to the context, but it seems there’s no way to get a list of all publishers in that template. But there is: all generic views take an extra optional parameter, extra_context. This is a dictionary of extra objects that will be added to the template’s context. So, to provide the list of all publishers on the detail detail view, we’d use an info dict like this:
publisher_info = {
“queryset” : Publisher.objects.all(),
“template_object_name” : “publisher”,
“extra_context” : {“book_list” : Book.objects.all()}
}
This would populate a {{ book_list }} variable in the template context. This pattern can be used to pass any information down into the template for the generic view. It’s very handy. However, there’s actually a subtle bug here — can you spot it?
The problem has to do with when the queries in extra_context are evaluated. Because this example puts Publisher.objects.all() in the URLconf, it will be evaluated only once (when the URLconf is first loaded). Once you add or remove publishers, you’ll notice that the generic view doesn’t reflect those changes until you reload the Web server
Note – This problem doesn’t apply to the queryset generic view argument. Since Django knows that particular QuerySet should never be cached, the generic view takes care of clearing the cache when each view is rendered. The solution is to use a callback in extra_context instead of a value. Any callable (i.e., a function) that’s passed to extra_context will be evaluated when the view is rendered (instead of only once). You could do this with an explicitly defined function:
def get_books():
return Book.objects.all()
publisher_info = {
“queryset” : Publisher.objects.all(),
“template_object_name” : “publisher”,
“extra_context” : {“book_list” : get_books}
}
or you could use a less obvious but shorter version that relies on the fact that
Publisher.objects.all is itself a callable:
publisher_info = {
“queryset” : Publisher.objects.all(),
“template_object_name” : “publisher”,
“extra_context” : {“book_list” : Book.objects.all}
}
Notice the lack of parentheses after Book.objects.all; this references the function without actually calling it (which the generic view will do later).
Viewing Subsets of Objects – Now let’s take a closer look at this queryset key we’ve been using all along. Most generic views take one of these queryset arguments — it’s how the view knows which set of objects to display. To pick a simple example, we might want to order a list of books by publication date, with the most recent first:
book_info = {
“queryset” : Book.objects.all().order_by(“-publication_date”),
}
urlpatterns = patterns(”,
(r’^publishers/$’, list_detail.object_list, publisher_info),
(r’^books/$’, list_detail.object_list, book_info),
)
That’s a pretty simple example, but it illustrates the idea nicely. Of course, you’ll usually want to do more than just reorder objects. If you want to present a list of books by a particular publisher, you can use the same technique:
apress_books = {
“queryset”: Book.objects.filter(publisher__name=”Apress Publishing”),
“template_name” : “books/apress_list.html”
}
urlpatterns = patterns(”,
(r’^publishers/$’, list_detail.object_list, publisher_info),
(r’^books/apress/$’, list_detail.object_list, apress_books),
)
Notice that along with a filtered queryset, we’re also using a custom template name. If we didn’t, the generic view would use the same template as the “vanilla” object list, which might not be what we want. Also notice that this isn’t a very elegant way of doing publisher-specific books. If we want to add another publisher page, we’d need another handful of lines in the URLconf, and more than a few publishers would get unreasonable. We’ll deal with this problem in the next section.
Note – If you get a 404 when requesting /books/apress/, check to ensure you actually have a Publisher with the name ‘Apress Publishing’. Generic views have an allow_empty parameter for this case.
Complex Filtering with Wrapper Functions – Another common need is to filter down the objects given in a list page by some key in the URL. Earlier we hard-coded the publisher’s name in the URLconf, but what if we wanted to write a view that displayed all the books by some arbitrary publisher? We can “wrap” the object_list generic view to avoid writing a lot of code by hand. As usual, we’ll start by writing a URLconf:
urlpatterns = patterns(”,
(r’^publishers/$’, list_detail.object_list, publisher_info),
(r’^books/(w+)/$’, books_by_publisher),
)
Next, we’ll write the books_by_publisher view itself:
from django.http import Http404
from django.views.generic import list_detail
from mysite.books.models import Book, Publisher
def books_by_publisher(request, name):
# Look up the publisher (and raise a 404 if it can’t be found).
try:
publisher = Publisher.objects.get(name__iexact=name)
except Publisher.DoesNotExist:
raise Http404
# Use the object_list view for the heavy lifting.
return list_detail.object_list(
request,
queryset = Book.objects.filter(publisher=publisher),
template_name = “books/books_by_publisher.html”,
template_object_name = “books”,
extra_context = {“publisher” : publisher}
)
This works because there’s really nothing special about generic views — they’re just Python functions. Like any view function, generic views expect a certain set of arguments and return HttpResponse objects. Thus, it’s incredibly easy to wrap a small function around a generic view that does additional work before handing things off to the generic view.
Note – Notice that in the preceding example we passed the current publisher being displayed in the extra_context. This is usually a good idea in wrappers of this nature; it lets the template know which “parent” object is currently being browsed.
Performing Extra Work – The last common pattern we’ll look at involves doing some extra work before or after calling the generic view. Imagine we had a last_accessed field on our Author object that we were using to keep track of the last time anybody looked at that author. The generic object_detail view, of course, wouldn’t know anything about this field, but once again we could easily write a custom view to keep that field updated. First, we’d need to add an author detail bit in the URLconf to point to a custom view:
from mysite.books.views import author_detail
urlpatterns = patterns(”,
#…
(r’^authors/(?P<author_id>d+)/$’, author_detail),
)
Then we’d write our wrapper function:
import datetime
from mysite.books.models import Author
from django.views.generic import list_detail
from django.shortcuts import get_object_or_404
def author_detail(request, author_id):
# Look up the Author (and raise a 404 if she’s not found)
author = get_object_or_404(Author, pk=author_id)
# Record the last accessed date
author.last_accessed = datetime.datetime.now()
author.save()
# Show the detail page
return list_detail.object_detail(
request,
queryset = Author.objects.all(),
object_id = author_id,
)
Note – This code won’t actually work unless you add a last_accessed field to your Author model and create a books/author_detail.html template.
We can use a similar idiom to alter the response returned by the generic view. If we wanted to provide a downloadable plain-text version of the list of authors, we could use a view like this:
def author_list_plaintext(request):
response = list_detail.object_list(
request,
queryset = Author.objects.all(),
mimetype = “text/plain”,
template_name = “books/author_list.txt”
)
response[“Content-Disposition”] = “attachment; filename=authors.txt”
return response
This works because the generic views return simple HttpResponse objects that can be treated like dictionaries to set HTTP headers. This Content-Disposition business, by the way, instructs the browser to download and save the page instead of displaying it in the browser.