| 1 |
=================== |
|---|
| 2 |
Using generic views |
|---|
| 3 |
=================== |
|---|
| 4 |
|
|---|
| 5 |
Writing Web applications can be monotonous, because we repeat certain patterns |
|---|
| 6 |
again and again. In Django, the most common of these patterns have been |
|---|
| 7 |
abstracted into "generic views" that let you quickly provide common views of |
|---|
| 8 |
an object without actually needing to write any views. |
|---|
| 9 |
|
|---|
| 10 |
Django's generic views contain the following: |
|---|
| 11 |
|
|---|
| 12 |
* A set of views for doing list/detail interfaces (for example, |
|---|
| 13 |
Django's `documentation index`_ and `detail pages`_). |
|---|
| 14 |
|
|---|
| 15 |
* A set of views for year/month/day archive pages and associated |
|---|
| 16 |
detail and "latest" pages (for example, the Django weblog's year_, |
|---|
| 17 |
month_, day_, detail_, and latest_ pages). |
|---|
| 18 |
|
|---|
| 19 |
* A set of views for creating, editing, and deleting objects. |
|---|
| 20 |
|
|---|
| 21 |
.. _`documentation index`: http://www.djangoproject.com/documentation/ |
|---|
| 22 |
.. _`detail pages`: http://www.djangoproject.com/documentation/faq/ |
|---|
| 23 |
.. _year: http://www.djangoproject.com/weblog/2005/ |
|---|
| 24 |
.. _month: http://www.djangoproject.com/weblog/2005/jul/ |
|---|
| 25 |
.. _day: http://www.djangoproject.com/weblog/2005/jul/20/ |
|---|
| 26 |
.. _detail: http://www.djangoproject.com/weblog/2005/jul/20/autoreload/ |
|---|
| 27 |
.. _latest: http://www.djangoproject.com/weblog/ |
|---|
| 28 |
|
|---|
| 29 |
All of these views are used by creating configuration dictionaries in |
|---|
| 30 |
your URLconf files and passing those dictionaries as the third member of the |
|---|
| 31 |
URLconf tuple. For example, here's the URLconf for the simple weblog app that |
|---|
| 32 |
drives the blog on djangoproject.com:: |
|---|
| 33 |
|
|---|
| 34 |
from django.conf.urls.defaults import * |
|---|
| 35 |
|
|---|
| 36 |
info_dict = { |
|---|
| 37 |
'app_label': 'blog', |
|---|
| 38 |
'module_name': 'entries', |
|---|
| 39 |
'date_field': 'pub_date', |
|---|
| 40 |
} |
|---|
| 41 |
|
|---|
| 42 |
urlpatterns = patterns('django.views.generic.date_based', |
|---|
| 43 |
(r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>\w+)/$', 'object_detail', dict(info_dict, slug_field='slug')), |
|---|
| 44 |
(r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/$', 'archive_day', info_dict), |
|---|
| 45 |
(r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$', 'archive_month', info_dict), |
|---|
| 46 |
(r'^(?P<year>\d{4})/$', 'archive_year', info_dict), |
|---|
| 47 |
(r'^/?$', 'archive_index', info_dict), |
|---|
| 48 |
) |
|---|
| 49 |
|
|---|
| 50 |
As you can see, this URLconf defines a few options in ``info_dict`` that tell |
|---|
| 51 |
the generic view which model to use (``blog.entries`` in this case), as well as |
|---|
| 52 |
some extra information. |
|---|
| 53 |
|
|---|
| 54 |
Documentation of each generic view follows, along with a list of all keyword |
|---|
| 55 |
arguments that a generic view expects. Remember that as in the example above, |
|---|
| 56 |
arguments may either come from the URL pattern (as ``month``, ``day``, |
|---|
| 57 |
``year``, etc. do above) or from the additional-information dictionary (as for |
|---|
| 58 |
``app_label``, ``module_name``, etc.). |
|---|
| 59 |
|
|---|
| 60 |
Most of the generic views that follow require the ``app_label`` and |
|---|
| 61 |
``module_name`` keys. These values are easiest to explain through example:: |
|---|
| 62 |
|
|---|
| 63 |
>>> from django.models.blog import entries |
|---|
| 64 |
|
|---|
| 65 |
In the above line, ``blog`` is the ``app_label`` (the name of the file that |
|---|
| 66 |
holds all your model definitions) and ``entries`` is the ``module_name`` |
|---|
| 67 |
(either a pluralized, lowercased version of the model class name, or the value |
|---|
| 68 |
of the ``module_name`` option of your model). In the docs below, these keys |
|---|
| 69 |
will not be repeated, but each generic view requires them. |
|---|
| 70 |
|
|---|
| 71 |
Using "simple" generic views |
|---|
| 72 |
============================ |
|---|
| 73 |
|
|---|
| 74 |
The ``django.views.generic.simple`` module contains simple views to handle a |
|---|
| 75 |
couple of common cases: rendering a template when no view logic is needed, |
|---|
| 76 |
and issuing a redirect. These views are: |
|---|
| 77 |
|
|---|
| 78 |
``direct_to_template`` |
|---|
| 79 |
Renders a given template, passing it a ``{{ params }}`` template variable, |
|---|
| 80 |
which is a dictionary of the parameters captured in the URL. This requires |
|---|
| 81 |
the ``template`` argument. |
|---|
| 82 |
|
|---|
| 83 |
For example, given the following URL patterns:: |
|---|
| 84 |
|
|---|
| 85 |
urlpatterns = patterns('django.views.generic.simple', |
|---|
| 86 |
(r'^foo/$', 'direct_to_template', {'template': 'foo_index'}), |
|---|
| 87 |
(r'^foo/(?P<id>\d+)/$', 'direct_to_template', {'template': 'foo_detail'}), |
|---|
| 88 |
) |
|---|
| 89 |
|
|---|
| 90 |
... a request to ``/foo/`` would cause the ``foo_index`` template to be |
|---|
| 91 |
rendered, and a request to ``/foo/15/`` would cause the ``foo_detail`` |
|---|
| 92 |
template to be rendered with a context variable ``{{ params.id }}`` that is |
|---|
| 93 |
set to ``15``. |
|---|
| 94 |
|
|---|
| 95 |
``redirect_to`` |
|---|
| 96 |
Issue a redirect to a given URL. |
|---|
| 97 |
|
|---|
| 98 |
The given URL may contain dict-style string formatting, which will be |
|---|
| 99 |
interpolated against the params in the URL. For example, to redirect from |
|---|
| 100 |
``/foo/<id>/`` to ``/bar/<id>/``, you could use the following urlpattern:: |
|---|
| 101 |
|
|---|
| 102 |
urlpatterns = patterns('django.views.generic.simple', |
|---|
| 103 |
('^foo/(?p<id>\d+)/$', 'redirect_to', {'url' : '/bar/%(id)s/'}), |
|---|
| 104 |
) |
|---|
| 105 |
|
|---|
| 106 |
If the given URL is ``None``, an ``HttpResponseGone`` (410) will be issued. |
|---|
| 107 |
|
|---|
| 108 |
Using date-based generic views |
|---|
| 109 |
============================== |
|---|
| 110 |
|
|---|
| 111 |
Date-based generic views (in the module ``django.views.generic.date_based``) |
|---|
| 112 |
feature six functions for dealing with date-based data. Besides ``app_label`` |
|---|
| 113 |
and ``module_name``, all date-based generic views require that the |
|---|
| 114 |
``date_field`` argument be passed to them. This is the name of the field that |
|---|
| 115 |
stores the date the objects should key off of. |
|---|
| 116 |
|
|---|
| 117 |
Additionally, all date-based generic views have the following optional |
|---|
| 118 |
arguments: |
|---|
| 119 |
|
|---|
| 120 |
======================= ================================================== |
|---|
| 121 |
Argument Description |
|---|
| 122 |
======================= ================================================== |
|---|
| 123 |
``template_name`` Overrides the default template name used for the |
|---|
| 124 |
view. |
|---|
| 125 |
|
|---|
| 126 |
``extra_lookup_kwargs`` A dictionary of extra lookup parameters (see |
|---|
| 127 |
the `database API docs`_). |
|---|
| 128 |
|
|---|
| 129 |
``extra_context`` A dictionary of extra data to put into the |
|---|
| 130 |
template's context. |
|---|
| 131 |
======================= ================================================== |
|---|
| 132 |
|
|---|
| 133 |
.. _`database API docs`: http://www.djangoproject.com/documentation/db_api/ |
|---|
| 134 |
|
|---|
| 135 |
The date-based generic functions are: |
|---|
| 136 |
|
|---|
| 137 |
``archive_index`` |
|---|
| 138 |
A top-level index page showing the "latest" objects. Has an optional |
|---|
| 139 |
argument, ``num_latest``, which is the number of items to display on the |
|---|
| 140 |
page (defaults to 15). |
|---|
| 141 |
|
|---|
| 142 |
Uses the template ``app_label/module_name_archive`` by default. |
|---|
| 143 |
|
|---|
| 144 |
Has the following template context: |
|---|
| 145 |
|
|---|
| 146 |
``date_list`` |
|---|
| 147 |
List of years with objects |
|---|
| 148 |
``latest`` |
|---|
| 149 |
Latest objects by date |
|---|
| 150 |
|
|---|
| 151 |
``archive_year`` |
|---|
| 152 |
Yearly archive. Requires that the ``year`` argument be present in the URL |
|---|
| 153 |
pattern. |
|---|
| 154 |
|
|---|
| 155 |
Uses the template ``app_label/module_name_archive_year`` by default. |
|---|
| 156 |
|
|---|
| 157 |
Has the following template context: |
|---|
| 158 |
|
|---|
| 159 |
``date_list`` |
|---|
| 160 |
List of months in the given year with objects |
|---|
| 161 |
``year`` |
|---|
| 162 |
The given year (an integer) |
|---|
| 163 |
|
|---|
| 164 |
``archive_month`` |
|---|
| 165 |
Monthly archive. Requires that ``year`` and ``month`` arguments be given. |
|---|
| 166 |
You can pass the additional option ``month_format`` if you'd like to change |
|---|
| 167 |
the way months are specified in the URL. |
|---|
| 168 |
|
|---|
| 169 |
``month_format`` is a format string in the same syntax accepted by Python's |
|---|
| 170 |
``time.strftime``. (See the `strftime docs`_.) It's set to ``"%b"`` by |
|---|
| 171 |
default, which is a three-letter month abbreviation. To change it to use |
|---|
| 172 |
numbers, use ``"%m"``. |
|---|
| 173 |
|
|---|
| 174 |
Uses the template ``app_label/module_name_archive_month`` by default. |
|---|
| 175 |
|
|---|
| 176 |
Has the following template context: |
|---|
| 177 |
|
|---|
| 178 |
``month`` |
|---|
| 179 |
The given month (a datetime.datetime object) |
|---|
| 180 |
``object_list`` |
|---|
| 181 |
List of objects published in the given month |
|---|
| 182 |
|
|---|
| 183 |
``archive_day`` |
|---|
| 184 |
Daily archive. Requires that ``year``, ``month``, and ``day`` arguments be |
|---|
| 185 |
given. |
|---|
| 186 |
|
|---|
| 187 |
As in ``archive_month``, you can pass an optional ``month_format``. You can |
|---|
| 188 |
also pass ``day_format``, which defaults to ``"%d"`` (day of the month as a |
|---|
| 189 |
decimal number, 1-31). |
|---|
| 190 |
|
|---|
| 191 |
Uses the template ``app_label/module_name_archive_day`` by default. |
|---|
| 192 |
|
|---|
| 193 |
Has the following template context: |
|---|
| 194 |
|
|---|
| 195 |
``object_list`` |
|---|
| 196 |
List of objects published this day |
|---|
| 197 |
``day`` |
|---|
| 198 |
The given day (a datetime.datetime object) |
|---|
| 199 |
``previous_day`` |
|---|
| 200 |
The previous day (a datetime.datetime object) |
|---|
| 201 |
``next_day`` |
|---|
| 202 |
The next day (a datetime.datetime object), or None if the given |
|---|
| 203 |
day is today |
|---|
| 204 |
|
|---|
| 205 |
``archive_today`` |
|---|
| 206 |
List of objects for today. Exactly the same as ``archive_day``, except |
|---|
| 207 |
the year/month/day arguments are not given, and today's date is used |
|---|
| 208 |
instead. |
|---|
| 209 |
|
|---|
| 210 |
``object_detail`` |
|---|
| 211 |
Individual object page. Requires ``year``/``month``/``day`` arguments like |
|---|
| 212 |
``archive_day``. This function can be used with two types of URLs: either |
|---|
| 213 |
``/year/month/day/slug/`` or ``/year/month/day/object_id/``. |
|---|
| 214 |
|
|---|
| 215 |
If you're using the slug-style URLs, you'll need to have a ``slug`` item in |
|---|
| 216 |
your URLconf, and you'll need to pass a ``slug_field`` key in your info |
|---|
| 217 |
dictionary to indicate the name of the slug field. |
|---|
| 218 |
|
|---|
| 219 |
If your using the object_id-style URLs, you'll just need to give the URL |
|---|
| 220 |
pattern an ``object_id`` field. |
|---|
| 221 |
|
|---|
| 222 |
You can also pass the ``template_name_field`` argument to indicate that the |
|---|
| 223 |
the object stores the name of its template in a field on the object itself. |
|---|
| 224 |
|
|---|
| 225 |
As in ``archive_day``, ``object_detail`` takes optional ``month_format`` |
|---|
| 226 |
and ``day_format`` parameters. |
|---|
| 227 |
|
|---|
| 228 |
.. _strftime docs: http://www.python.org/doc/current/lib/module-time.html#l2h-1941 |
|---|
| 229 |
|
|---|
| 230 |
Using list/detail generic views |
|---|
| 231 |
=============================== |
|---|
| 232 |
|
|---|
| 233 |
The list-detail generic-view framework (in the |
|---|
| 234 |
``django.views.generic.list_detail`` module) is similar to the date-based one, |
|---|
| 235 |
except the former simply has two views: a list of objects and an individual |
|---|
| 236 |
object page. |
|---|
| 237 |
|
|---|
| 238 |
All these views take the same three optional arguments as the date-based ones |
|---|
| 239 |
-- and, clearly, they don't accept the ``date_field`` argument. |
|---|
| 240 |
|
|---|
| 241 |
Individual views are: |
|---|
| 242 |
|
|---|
| 243 |
``object_list`` |
|---|
| 244 |
List of objects. |
|---|
| 245 |
|
|---|
| 246 |
Takes the following optional arguments: |
|---|
| 247 |
|
|---|
| 248 |
======================= ================================================= |
|---|
| 249 |
Argument Description |
|---|
| 250 |
======================= ================================================= |
|---|
| 251 |
``paginate_by`` If set to an integer, the view will paginate |
|---|
| 252 |
objects with ``paginate_by`` objects per page. |
|---|
| 253 |
The view will expect a ``page`` GET param with |
|---|
| 254 |
the (zero-indexed) page number. |
|---|
| 255 |
|
|---|
| 256 |
``allow_empty`` If ``False`` and there are no objects to display, |
|---|
| 257 |
the view will raise a 404 instead of displaying |
|---|
| 258 |
an empty index page. ``False`` is default. |
|---|
| 259 |
======================= ================================================= |
|---|
| 260 |
|
|---|
| 261 |
Uses the template ``app_label/module_name_list`` by default. |
|---|
| 262 |
|
|---|
| 263 |
Has the following template context: |
|---|
| 264 |
|
|---|
| 265 |
``object_list`` |
|---|
| 266 |
List of objects |
|---|
| 267 |
``is_paginated`` |
|---|
| 268 |
Are the results paginated? Either True or False |
|---|
| 269 |
|
|---|
| 270 |
If the results are paginated, the context will have some extra variables: |
|---|
| 271 |
|
|---|
| 272 |
``results_per_page`` |
|---|
| 273 |
Number of objects per page |
|---|
| 274 |
``has_next`` |
|---|
| 275 |
Is there a next page? |
|---|
| 276 |
``has_previous`` |
|---|
| 277 |
Is there a previous page? |
|---|
| 278 |
``page`` |
|---|
| 279 |
The current page number |
|---|
| 280 |
``next`` |
|---|
| 281 |
The next page number |
|---|
| 282 |
``previous`` |
|---|
| 283 |
The previous page |
|---|
| 284 |
``pages`` |
|---|
| 285 |
Number of pages total |
|---|
| 286 |
``hits`` |
|---|
| 287 |
Total number of objects |
|---|
| 288 |
|
|---|
| 289 |
``object_detail`` |
|---|
| 290 |
Object detail page. This works like and takes the same arguments as |
|---|
| 291 |
the date-based ``object_detail`` above, except this one, obviously, |
|---|
| 292 |
does not take the year/month/day arguments. |
|---|
| 293 |
|
|---|
| 294 |
Using create/update/delete generic views |
|---|
| 295 |
======================================== |
|---|
| 296 |
|
|---|
| 297 |
The ``django.views.generic.create_update`` module contains a set of functions |
|---|
| 298 |
for creating, editing and deleting objects. These views take the same global |
|---|
| 299 |
arguments as the above sets of generic views. They also have a |
|---|
| 300 |
``login_required`` argument which, if ``True``, requires the user to be logged |
|---|
| 301 |
in to have access to the page. (``login_required`` defaults to ``False``.) |
|---|
| 302 |
|
|---|
| 303 |
The create/update/delete views are: |
|---|
| 304 |
|
|---|
| 305 |
``create_object`` |
|---|
| 306 |
Create a new object. Has an extra optional argument, ``post_save_redirect``, |
|---|
| 307 |
which is a URL to which the view will redirect after saving the object. |
|---|
| 308 |
It defaults to ``object.get_absolute_url()``. |
|---|
| 309 |
|
|---|
| 310 |
``post_save_redirect`` may contain dictionary string formatting, which will |
|---|
| 311 |
be interpolated against the object's field attributes. For example, you |
|---|
| 312 |
could use ``post_save_redirect="/polls/%(slug)s/"``. |
|---|
| 313 |
|
|---|
| 314 |
Uses the template ``app_label/module_name_form`` by default. This is the |
|---|
| 315 |
same template as the ``update_object`` view below. Your template can tell |
|---|
| 316 |
the different by the presence or absence of ``{{ object }}`` in the |
|---|
| 317 |
context. |
|---|
| 318 |
|
|---|
| 319 |
Has the following template context: |
|---|
| 320 |
|
|---|
| 321 |
form |
|---|
| 322 |
The form wrapper for the object |
|---|
| 323 |
|
|---|
| 324 |
.. admonition:: Note |
|---|
| 325 |
|
|---|
| 326 |
See the `manipulator and formfield documentation`_ for more information |
|---|
| 327 |
about using form wrappers in templates. |
|---|
| 328 |
|
|---|
| 329 |
.. _`manipulator and formfield documentation`: http://www.djangoproject.com/documentation/forms/ |
|---|
| 330 |
|
|---|
| 331 |
``update_object`` |
|---|
| 332 |
Edit an existing object. Has the same extra slug/ID parameters as |
|---|
| 333 |
``list_detail.object_detail`` does (see above), and the same |
|---|
| 334 |
``post_save_redirect`` as ``create_object`` does. |
|---|
| 335 |
|
|---|
| 336 |
Uses the template ``app_label/module_name_form`` by default. |
|---|
| 337 |
|
|---|
| 338 |
Has the following template context: |
|---|
| 339 |
|
|---|
| 340 |
form |
|---|
| 341 |
The form wrapper for the object |
|---|
| 342 |
object |
|---|
| 343 |
The original object being edited |
|---|
| 344 |
|
|---|
| 345 |
``delete_object`` |
|---|
| 346 |
Delete an existing object. The given object will only actually be deleted |
|---|
| 347 |
if the request method is POST. If this view is fetched with GET, it will |
|---|
| 348 |
display a confirmation page that should contain a form that POSTs to the |
|---|
| 349 |
same URL. |
|---|
| 350 |
|
|---|
| 351 |
You must provide the ``post_delete_redirect`` argument to this function, so |
|---|
| 352 |
that the view knows where to go after the object is deleted. |
|---|
| 353 |
|
|---|
| 354 |
If fetched with GET, it uses the template |
|---|
| 355 |
``app_label/module_name_confirm_delete`` by default. It uses no template |
|---|
| 356 |
if POSTed -- it simply deletes the object and redirects. |
|---|
| 357 |
|
|---|
| 358 |
Has the following template context: |
|---|
| 359 |
|
|---|
| 360 |
object |
|---|
| 361 |
The object about to be deleted |
|---|