Hour 12. Utilizing Generic Views
What You'll Learn in This Hour |
|
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
Argument | Description |
---|
allow_empty | Boolean. 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_future | Boolean. Defaults to False. If set to True, date-based views display dates even if they are in the future. |
context_processors | A list of template-context processors to apply to the views template. |
date_field | Specifies the name of the DateField or DateTimeField of the model that date-based views use to query dates to build a list of objects. |
day | Specifies the day, formatted by the day_format argument, that date-based views use to query dates to build a list of objects. |
day_format | Defaults to %d. Specifies the format to use when specifying the day argument. |
extra_context | A dictionary object that contains whatever extra objects, functions, and auxiliary information you want to pass to the view. |
login_required | Boolean. Defaults to False. If set to True, displays the view only if the user is logged in. |
make_object_list | Boolean. 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. |
mimetype | Defaults to DEFAULT_CONTENT_TYPE. Specifies the MIME type to use for the resulting document. |
model | Specifies which model to use when building forms to create, update, and delete generic views. |
month | Specifies the month, formatted by the month_format argument, that date-based views use to query dates to build a list of objects. |
month_format | Defaults to %d. Specifies the format to use when specifying the month argument. |
num_latest | Defaults to 15. Specifies the number objects to send to the template as the latest context variable. |
object_id | Specifies the primary key value to use when accessing objects directly. |
page | Specifies a 1-based integer designating the current page number. |
paginate_by | An 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_redirect | Specifies an URL to redirect the browser to after the delete operation. |
post_save_redirect | Specifies an URL to redirect the browser to after the save operation. |
queryset | Specifies a QuerySet object to use as a list of objects. |
slug_field | A slug and slug_field can be used instead of the object_id argument in some views. |
template | The full name and path, relative to the template directory, to use in the direct_to_template view. |
template_loader | The template loader to use when loading the template. |
template_name | The full name and path, relative to the template directory, of a template file to use to render the page. |
template_object_name | Designates the name of the context variable that is assigned to the object. |
url | Specifies the URL to redirect the browser to in the redirect_to view. |
week | Specifies the two-digit week that date-based views use to query dates to build a list of objects. |
year | Specifies 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
Variable | Description |
---|
date_list | A 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. |
day | A datetime object representing the day of the date-based view. |
first_on_page | The 1-based index for the first result on the current page in pagination. |
form | A Form object created for a model in the object creation, update, and deletion views. |
has_next | Boolean. Is True if there is a next page in pagination. |
has_previous | Boolean. Is True if there is a previous page in pagination. |
hits | The total number of pages in pagination. |
is_paginated | Boolean. Is True if the paginate_by argument was added to the view. |
last_on_page | The 1-based index for the last result on the current page in pagination. |
latest | A list of the latest arguments in the system. The number of latest objects corresponds to the num_latest argument. |
month | A datetime object representing the month of the date-based view. |
next | The 1-based page number for the next page in pagination. |
next_day | A datetime object representing the next day of the date-based view. |
next_month | A datetime object representing the next month of the date-based view. |
object | An object passed to the template by the view function. The context variable object is the default value of the template_object_name argument. |
object_list | A list of objects passed to the template by the view function. |
page | The current page number in pagination. |
pages | The total number of pages in pagination. |
params | A dictionary of parameters captured by the URLconf and passed to the direct_to_template view. |
previous | The 1-based page number for the previous page in pagination. |
previous_day | A datetime object representing the previous day of the date-based view. |
previous_month | A datetime object representing the previous month of the date-based view. |
results_per_page | The number that was specified by the paginate_by argument. |
week | A datetime object representing the week of the date-based view. |
year | A 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: