Tutorial O’ The Day: Django Generic Views
One of the great charms of Django is the amount of work it does for you. It’s literally possible to build complex applications that mirror the features of say, WordPress, in little more than a hundred lines of code.
How the heck does Django do it? Well one of the great tools that Django puts at your disposal is something called generic views. Views are simply python functions that get called whenever a browser requests a page.
There’s a myriad of ways to storing and retrieve data in a web application, but date-based structures are pretty common. For instance, the url of this page contains something like ‘…/2007/01/…’ which is a date-based archive.
Rather than requiring that you write your own code every time you build a site that uses date-based archives, the designers of Django included some generic views to handle common cases. In this case, were this site powered by Django, which regrettably it is not, but were it, we could pass the date from the url to django in one easy line of code:
(r'(?P<year>\d{4})/(?P<month>[a-z]{3})/$', ‘django.views.generic.date_based.archive_month’, data_dict),
(note that the above code should be all one line)
Okay maybe it looks confusing, but it’s really not. The first part is just a regular expression that captures the url and passes it to the generic view archive_month. The last bit is a python dictionary which would tell Django what data model to use for this page.
Another common task web applications perform is displaying a list of content and to this end there are Django generic views for lists.
Which brings us to today’s tutorial. Generic views are great, but what if they don’t exactly fit your application? Well, it’s pretty easy to extend generic views and James Bennet has a great tutorial on his blog The B-list that runs through the basics of extending, tweaking and otherwise making generic views do what you want.
Mr. Bennet also has a number of other very useful and easy-to-follow Django tutorials, try digging through the rest of his Django archives.

