Monday, 25 January 2010

Using django's generic views for listing objects

Django comes equipped with generic views: A set of pre-made view functions that help you do repetitive stuff with less hassles.

One of the most common thing that you will do in a web application is to pull data from the database and show them to the user, as a list or table. Using django's object_list generic view, you can do this with minimum code.

An example of using the generic view



#!/usr/bin/env python
# -*- coding: utf-8 -*-

# import the generic views
from django.views.generic.list_detail import object_list
from models import MyObjects

def view_list(request):

template_path = "mytemplate.html"
response_dict = {}

myobjects = MyObject.objects.filter(name__istartswith="Mike")

return object_list(request, queryset=myobjects,
template_name=template_path,
paginate_by=3,
page=page,
template_object_name="templateobject",
extra_context=response_dict)



The above view will return to your template a list called "templateobject_list" which contains models of myobjects.
For more details on the parameters for object_list(), check the Django documentation here: Django object_list manual

No comments: