Previous Page Next Page

Hour 12. Utilizing Generic Views

What You'll Learn in This Hour

  • How to use simple generic views

  • How to display a list of objects using generic views

  • How to display object details using generic views

  • How to display date-based object indexes using generic views

  • How to use generic views to create objects

  • How to use generic views to update objects

  • How to use generic views to delete objects

Django provides a set of easy-to-use packages called generic views that allow you to generate basic generic views quickly. Generic views do a good job of abstracting common tasks such as building web views to display lists of objects, as well as create, update, and delete objects.

Basically, generic views do the work that is normally done in an application's views.py file. Using generic views, you can create useful views without having to use any Python code.

The following sections describe generic views and how to use them to display objects, lists of objects, and forms to create, change, and delete objects.

Understanding Generic Views

Generic views are easy to implement. To implement a generic view, you create a template for the generic view to render and then add an URL pattern to the URLconf file that enables the view.

The four basic parts of implementing generic views are the arguments dictionary, URL pattern, context variables, and HTML template. The following sections discuss each part.

Arguments Dictionary

The arguments dictionary is a Python dictionary of arguments that are passed to the generic view function when the URL is accessed. Each generic view has a list of required and optional arguments. The arguments allow you to define the view's behavior and attributes.

Some arguments define the behavior of the view function, and others are used as data in the template file. For example, the following dictionary defines arguments that can be passed to an object_list generic view:

quote_list_info = {
    'queryset' : Quote.objects.all(),
    'allow_empty' : True,
}

The argument queryset is a QuerySet object of all objects in the Quote model. The queryset argument gives the generic list a set of data that can be accessed from the generic view template. The allow_empty argument tells the generic list function to accept an empty list.

The arguments that are available to the generic view functions handle most of the views' needs. However, sometimes you want to pass your own custom variables to the view. Django provides the extra_context argument to solve this problem. The extra_context argument is a dictionary that defines auxiliary data that you want to pass to the template. You can pass objects or callables as part of the extra_context dictionary.

Watch Out!

Be careful if you pass QuerySet objects as part of the extra_context dictionary. QuerySets are cached when they are first evaluated, so the data might be stale by the time it is passed to the view. If you need fresh data in the QuerySet, you can pass the QuerySet by passing a function and having the function create the QuerySet.


Table 12.1 lists all the arguments that can be used in the different generic views.

Table 12.1. Generic View Arguments That Can Be Added to the Info Dictionary for Generic Views
ArgumentDescription
allow_emptyBoolean. Defaults to False. If set to True, the page is displayed even if no objects are in the list. Otherwise, a 404 error is displayed.
allow_futureBoolean. Defaults to False. If set to True, date-based views display dates even if they are in the future.
context_processorsA list of template-context processors to apply to the views template.
date_fieldSpecifies the name of the DateField or DateTimeField of the model that date-based views use to query dates to build a list of objects.
daySpecifies the day, formatted by the day_format argument, that date-based views use to query dates to build a list of objects.
day_formatDefaults to %d. Specifies the format to use when specifying the day argument.
extra_contextA dictionary object that contains whatever extra objects, functions, and auxiliary information you want to pass to the view.
login_requiredBoolean. Defaults to False. If set to True, displays the view only if the user is logged in.
make_object_listBoolean. Defaults to False. If set to True, the archive_year view retrieves a list of objects and passes it to the template as the object_list context variable.
mimetypeDefaults to DEFAULT_CONTENT_TYPE. Specifies the MIME type to use for the resulting document.
modelSpecifies which model to use when building forms to create, update, and delete generic views.
monthSpecifies the month, formatted by the month_format argument, that date-based views use to query dates to build a list of objects.
month_formatDefaults to %d. Specifies the format to use when specifying the month argument.
num_latestDefaults to 15. Specifies the number objects to send to the template as the latest context variable.
object_idSpecifies the primary key value to use when accessing objects directly.
pageSpecifies a 1-based integer designating the current page number.
paginate_byAn integer. Specifies the number of objects to be displayed per page. If you use the paginate_by argument, a page argument is required as well.
post_delete_redirectSpecifies an URL to redirect the browser to after the delete operation.
post_save_redirectSpecifies an URL to redirect the browser to after the save operation.
querysetSpecifies a QuerySet object to use as a list of objects.
slug_fieldA slug and slug_field can be used instead of the object_id argument in some views.
templateThe full name and path, relative to the template directory, to use in the direct_to_template view.
template_loaderThe template loader to use when loading the template.
template_nameThe full name and path, relative to the template directory, of a template file to use to render the page.
template_object_nameDesignates the name of the context variable that is assigned to the object.
urlSpecifies the URL to redirect the browser to in the redirect_to view.
weekSpecifies the two-digit week that date-based views use to query dates to build a list of objects.
yearSpecifies the four-digit year that date-based views use to query dates to build a list of objects.


By the Way

Which arguments are required and which are optional for each generic view function depends on which view function you are using. This topic is discussed later in this hour.


URL Pattern

Generic template URL patterns follow the same syntax as normal URL patterns. The only differences are that the second argument points to a generic view package instead of a view function in the application, and the dictionary of arguments is required as the third argument.

By the Way

Generic URL patterns can be added to the same patterns statement in the URLconf file. However, it might be a good idea to separate them to make the URLconf more manageable.


For example, to create an URL pattern to access the object_list generic view, you would define an argument dictionary and add an URL pattern similar to the following to the URLconf file:

obj_dict = {
    'queryset' : Quotes.objects.all()
    'allow_empty' : True
}
urlpatterns = patterns('django.views.generic.list_detail',
    (r'^obj_list/$', object_list, obj_dict),
}

Context Variables

Context variables are variables that can be accessed from within the template file. Context variables in generic views are the same as creating a dictionary and passing it to the render_to_response() function.

Table 12.2 lists the context variables that get passed to the template.

Table 12.2. Context Variables Generated by Generic Views That Are Available in the Templates
VariableDescription
date_listA list of datetime objects representing all the dates that have objects available for the date-based view. For archive_index, the objects are year-based for all objects. For archive_year, the objects are month-based for one year.
dayA datetime object representing the day of the date-based view.
first_on_pageThe 1-based index for the first result on the current page in pagination.
formA Form object created for a model in the object creation, update, and deletion views.
has_nextBoolean. Is True if there is a next page in pagination.
has_previousBoolean. Is True if there is a previous page in pagination.
hitsThe total number of pages in pagination.
is_paginatedBoolean. Is True if the paginate_by argument was added to the view.
last_on_pageThe 1-based index for the last result on the current page in pagination.
latestA list of the latest arguments in the system. The number of latest objects corresponds to the num_latest argument.
monthA datetime object representing the month of the date-based view.
nextThe 1-based page number for the next page in pagination.
next_dayA datetime object representing the next day of the date-based view.
next_monthA datetime object representing the next month of the date-based view.
objectAn object passed to the template by the view function. The context variable object is the default value of the template_object_name argument.
object_listA list of objects passed to the template by the view function.
pageThe current page number in pagination.
pagesThe total number of pages in pagination.
paramsA dictionary of parameters captured by the URLconf and passed to the direct_to_template view.
previousThe 1-based page number for the previous page in pagination.
previous_dayA datetime object representing the previous day of the date-based view.
previous_monthA datetime object representing the previous month of the date-based view.
results_per_pageThe number that was specified by the paginate_by argument.
weekA datetime object representing the week of the date-based view.
yearA datetime object representing the year of the date-based view.


By the Way

Which context variables that are available in the template for each generic view depends on which view function rendered it. This topic is discussed later in this hour.


Generic HTML Template

Generic templates are the same as other Django HTML template files. You need to create a template file to render each generic view. The context variables listed in the preceding section can be accessed from the generic view.

For example, you would use the following code to access the year context variable of a django.views.generic.date_based.archive_year view from the template:

{{ year }}

Previous Page Next Page