PageRenderTime 60ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/docs/ref/class-based-views.txt

https://code.google.com/p/mango-py/
Plain Text | 1323 lines | 902 code | 421 blank | 0 comment | 0 complexity | fb26d0d6fbb2a280043650b9d46937cf MD5 | raw file
Possible License(s): BSD-3-Clause
  1. =========================
  2. Class-based generic views
  3. =========================
  4. .. versionadded:: 1.3
  5. .. note::
  6. Prior to Django 1.3, generic views were implemented as functions. The
  7. function-based implementation has been deprecated in favor of the
  8. class-based approach described here.
  9. For details on the previous generic views implementation,
  10. see the :doc:`topic guide </topics/generic-views>` and
  11. :doc:`detailed reference </ref/generic-views>`.
  12. Writing Web applications can be monotonous, because we repeat certain patterns
  13. again and again. Django tries to take away some of that monotony at the model
  14. and template layers, but Web developers also experience this boredom at the view
  15. level.
  16. A general introduction to class-based generic views can be found in the
  17. :doc:`topic guide </topics/class-based-views>`.
  18. This reference contains details of Django's built-in generic views, along with
  19. a list of the keyword arguments that each generic view expects. Remember that
  20. arguments may either come from the URL pattern or from the ``extra_context``
  21. additional-information dictionary.
  22. Most generic views require the ``queryset`` key, which is a ``QuerySet``
  23. instance; see :doc:`/topics/db/queries` for more information about ``QuerySet``
  24. objects.
  25. Mixins
  26. ======
  27. A mixin class is a way of using the inheritance capabilities of
  28. classes to compose a class out of smaller pieces of behavior. Django's
  29. class-based generic views are constructed by composing mixins into
  30. usable generic views.
  31. For example, the :class:`~django.views.generic.base.detail.DetailView`
  32. is composed from:
  33. * :class:`~django.db.views.generic.base.View`, which provides the
  34. basic class-based behavior
  35. * :class:`~django.db.views.generic.detail.SingleObjectMixin`, which
  36. provides the utilities for retrieving and displaying a single object
  37. * :class:`~django.db.views.generic.detail.SingleObjectTemplateResponseMixin`,
  38. which provides the tools for rendering a single object into a
  39. template-based response.
  40. When combined, these mixins provide all the pieces necessary to
  41. provide a view over a single object that renders a template to produce
  42. a response.
  43. Django provides a range of mixins. If you want to write your own
  44. generic views, you can build classes that compose these mixins in
  45. interesting ways. Alternatively, you can just use the pre-mixed
  46. `Generic views`_ that Django provides.
  47. .. note::
  48. When the documentation for a view gives the list of mixins, that view
  49. inherits all the properties and methods of that mixin.
  50. Simple mixins
  51. -------------
  52. .. currentmodule:: django.views.generic.base
  53. TemplateResponseMixin
  54. ~~~~~~~~~~~~~~~~~~~~~
  55. .. class:: TemplateResponseMixin()
  56. .. attribute:: template_name
  57. The path to the template to use when rendering the view.
  58. .. attribute:: response_class
  59. The response class to be returned by ``render_to_response`` method.
  60. Default is
  61. :class:`TemplateResponse <django.template.response.TemplateResponse>`.
  62. The template and context of ``TemplateResponse`` instances can be
  63. altered later (e.g. in
  64. :ref:`template response middleware <template-response-middleware>`).
  65. If you need custom template loading or custom context object
  66. instantiation, create a ``TemplateResponse`` subclass and assign it to
  67. ``response_class``.
  68. .. method:: render_to_response(context, **response_kwargs)
  69. Returns a ``self.response_class`` instance.
  70. If any keyword arguments are provided, they will be
  71. passed to the constructor of the response class.
  72. Calls :meth:`~TemplateResponseMixin.get_template_names()` to obtain the
  73. list of template names that will be searched looking for an existent
  74. template.
  75. .. method:: get_template_names()
  76. Returns a list of template names to search for when rendering the
  77. template.
  78. If :attr:`TemplateResponseMixin.template_name` is specified, the
  79. default implementation will return a list containing
  80. :attr:`TemplateResponseMixin.template_name` (if it is specified).
  81. Single object mixins
  82. --------------------
  83. .. currentmodule:: django.views.generic.detail
  84. SingleObjectMixin
  85. ~~~~~~~~~~~~~~~~~
  86. .. class:: SingleObjectMixin()
  87. .. attribute:: model
  88. The model that this view will display data for. Specifying ``model
  89. = Foo`` is effectively the same as specifying ``queryset =
  90. Foo.objects.all()``.
  91. .. attribute:: queryset
  92. A ``QuerySet`` that represents the objects. If provided, the value of
  93. :attr:`SingleObjectMixin.queryset` supersedes the value provided for
  94. :attr:`SingleObjectMixin.model`.
  95. .. attribute:: slug_field
  96. The name of the field on the model that contains the slug. By default,
  97. ``slug_field`` is ``'slug'``.
  98. .. attribute:: context_object_name
  99. Designates the name of the variable to use in the context.
  100. .. method:: get_object(queryset=None)
  101. Returns the single object that this view will display. If
  102. ``queryset`` is provided, that queryset will be used as the
  103. source of objects; otherwise,
  104. :meth:`~SingleObjectMixin.get_queryset` will be used.
  105. :meth:`~SingleObjectMixin.get_object` looks for a ``pk``
  106. argument in the arguments to the view; if ``pk`` is found,
  107. this method performs a primary-key based lookup using that
  108. value. If no ``pk`` argument is found, it looks for a ``slug``
  109. argument, and performs a slug lookup using the
  110. :attr:`SingleObjectMixin.slug_field`.
  111. .. method:: get_queryset()
  112. Returns the queryset that will be used to retrieve the object that
  113. this view will display. By default,
  114. :meth:`~SingleObjectMixin.get_queryset` returns the value of the
  115. :attr:`~SingleObjectMixin.queryset` attribute if it is set, otherwise
  116. it constructs a :class:`QuerySet` by calling the `all()` method on the
  117. :attr:`~SingleObjectMixin.model` attribute's default manager.
  118. .. method:: get_context_object_name(obj)
  119. Return the context variable name that will be used to contain the
  120. data that this view is manipulating. If
  121. :attr:`~SingleObjectMixin.context_object_name` is not set, the context
  122. name will be constructed from the ``object_name`` of the model that
  123. the queryset is composed from. For example, the model ``Article``
  124. would have context object named ``'article'``.
  125. .. method:: get_context_data(**kwargs)
  126. Returns context data for displaying the list of objects.
  127. **Context**
  128. * ``object``: The object that this view is displaying. If
  129. ``context_object_name`` is specified, that variable will also be
  130. set in the context, with the same value as ``object``.
  131. SingleObjectTemplateResponseMixin
  132. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  133. .. class:: SingleObjectTemplateResponseMixin()
  134. A mixin class that performs template-based response rendering for views
  135. that operate upon a single object instance. Requires that the view it is
  136. mixed with provides ``self.object``, the object instance that the view is
  137. operating on. ``self.object`` will usually be, but is not required to be,
  138. an instance of a Django model. It may be ``None`` if the view is in the
  139. process of constructing a new instance.
  140. **Extends**
  141. * :class:`~django.views.generic.base.TemplateResponseMixin`
  142. .. attribute:: template_name_field
  143. The field on the current object instance that can be used to determine
  144. the name of a candidate template. If either ``template_name_field`` or
  145. the value of the ``template_name_field`` on the current object instance
  146. is ``None``, the object will not be interrogated for a candidate
  147. template name.
  148. .. attribute:: template_name_suffix
  149. The suffix to append to the auto-generated candidate template name.
  150. Default suffix is ``_detail``.
  151. .. method:: get_template_names()
  152. Returns a list of candidate template names. Returns the following list:
  153. * the value of ``template_name`` on the view (if provided)
  154. * the contents of the ``template_name_field`` field on the
  155. object instance that the view is operating upon (if available)
  156. * ``<app_label>/<object_name><template_name_suffix>.html``
  157. Multiple object mixins
  158. ----------------------
  159. .. currentmodule:: django.views.generic.list
  160. MultipleObjectMixin
  161. ~~~~~~~~~~~~~~~~~~~
  162. .. class:: MultipleObjectMixin()
  163. A mixin that can be used to display a list of objects.
  164. If ``paginate_by`` is specified, Django will paginate the results returned
  165. by this. You can specify the page number in the URL in one of two ways:
  166. * Use the ``page`` parameter in the URLconf. For example, this is what
  167. your URLconf might look like::
  168. (r'^objects/page(?P<page>[0-9]+)/$', PaginatedView.as_view())
  169. * Pass the page number via the ``page`` query-string parameter. For
  170. example, a URL would look like this::
  171. /objects/?page=3
  172. These values and lists are 1-based, not 0-based, so the first page would be
  173. represented as page ``1``.
  174. For more on pagination, read the :doc:`pagination documentation
  175. </topics/pagination>`.
  176. As a special case, you are also permitted to use ``last`` as a value for
  177. ``page``::
  178. /objects/?page=last
  179. This allows you to access the final page of results without first having to
  180. determine how many pages there are.
  181. Note that ``page`` *must* be either a valid page number or the value
  182. ``last``; any other value for ``page`` will result in a 404 error.
  183. .. attribute:: allow_empty
  184. A boolean specifying whether to display the page if no objects are
  185. available. If this is ``False`` and no objects are available, the view
  186. will raise a 404 instead of displaying an empty page. By default, this
  187. is ``True``.
  188. .. attribute:: model
  189. The model that this view will display data for. Specifying ``model
  190. = Foo`` is effectively the same as specifying ``queryset =
  191. Foo.objects.all()``.
  192. .. attribute:: queryset
  193. A ``QuerySet`` that represents the objects. If provided, the value of
  194. :attr:`MultipleObjectMixin.queryset` supersedes the value provided for
  195. :attr:`MultipleObjectMixin.model`.
  196. .. attribute:: paginate_by
  197. An integer specifying how many objects should be displayed per page. If
  198. this is given, the view will paginate objects with
  199. :attr:`MultipleObjectMixin.paginate_by` objects per page. The view will
  200. expect either a ``page`` query string parameter (via ``GET``) or a
  201. ``page`` variable specified in the URLconf.
  202. .. attribute:: paginator_class
  203. The paginator class to be used for pagination. By default,
  204. :class:`django.core.paginator.Paginator` is used. If the custom paginator
  205. class doesn't have the same constructor interface as
  206. :class:`django.core.paginator.Paginator`, you will also need to
  207. provide an implementation for :meth:`MultipleObjectMixin.get_paginator`.
  208. .. attribute:: context_object_name
  209. Designates the name of the variable to use in the context.
  210. .. method:: get_queryset()
  211. Returns the queryset that represents the data this view will display.
  212. .. method:: paginate_queryset(queryset, page_size)
  213. Returns a 4-tuple containing (``paginator``, ``page``, ``object_list``,
  214. ``is_paginated``).
  215. Constructed by paginating ``queryset`` into pages of size ``page_size``.
  216. If the request contains a ``page`` argument, either as a captured URL
  217. argument or as a GET argument, ``object_list`` will correspond to the
  218. objects from that page.
  219. .. method:: get_paginate_by(queryset)
  220. Returns the number of items to paginate by, or ``None`` for no
  221. pagination. By default this simply returns the value of
  222. :attr:`MultipleObjectMixin.paginate_by`.
  223. .. method:: get_paginator(queryset, per_page, orphans=0, allow_empty_first_page=True)
  224. Returns an instance of the paginator to use for this view. By default,
  225. instantiates an instance of :attr:`paginator_class`.
  226. .. method:: get_allow_empty()
  227. Return a boolean specifying whether to display the page if no objects
  228. are available. If this method returns ``False`` and no objects are
  229. available, the view will raise a 404 instead of displaying an empty
  230. page. By default, this is ``True``.
  231. .. method:: get_context_object_name(object_list)
  232. Return the context variable name that will be used to contain
  233. the list of data that this view is manipulating. If
  234. ``object_list`` is a queryset of Django objects and
  235. :attr:`~MultipleObjectMixin.context_object_name` is not set,
  236. the context name will be the ``object_name`` of the model that
  237. the queryset is composed from, with postfix ``'_list'``
  238. appended. For example, the model ``Article`` would have a
  239. context object named ``article_list``.
  240. .. method:: get_context_data(**kwargs)
  241. Returns context data for displaying the list of objects.
  242. **Context**
  243. * ``object_list``: The list of objects that this view is displaying. If
  244. ``context_object_name`` is specified, that variable will also be set
  245. in the context, with the same value as ``object_list``.
  246. * ``is_paginated``: A boolean representing whether the results are
  247. paginated. Specifically, this is set to ``False`` if no page size has
  248. been specified, or if the available objects do not span multiple
  249. pages.
  250. * ``paginator``: An instance of
  251. :class:`django.core.paginator.Paginator`. If the page is not
  252. paginated, this context variable will be ``None``.
  253. * ``page_obj``: An instance of
  254. :class:`django.core.paginator.Page`. If the page is not paginated,
  255. this context variable will be ``None``.
  256. MultipleObjectTemplateResponseMixin
  257. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  258. .. class:: MultipleObjectTemplateResponseMixin()
  259. A mixin class that performs template-based response rendering for views
  260. that operate upon a list of object instances. Requires that the view it is
  261. mixed with provides ``self.object_list``, the list of object instances that
  262. the view is operating on. ``self.object_list`` may be, but is not required
  263. to be, a :class:`~django.db.models.Queryset`.
  264. **Extends**
  265. * :class:`~django.views.generic.base.TemplateResponseMixin`
  266. .. attribute:: template_name_suffix
  267. The suffix to append to the auto-generated candidate template name.
  268. Default suffix is ``_list``.
  269. .. method:: get_template_names()
  270. Returns a list of candidate template names. Returns the following list:
  271. * the value of ``template_name`` on the view (if provided)
  272. * ``<app_label>/<object_name><template_name_suffix>.html``
  273. Editing mixins
  274. --------------
  275. .. currentmodule:: django.views.generic.edit
  276. FormMixin
  277. ~~~~~~~~~
  278. .. class:: FormMixin()
  279. A mixin class that provides facilities for creating and displaying forms.
  280. .. attribute:: initial
  281. A dictionary containing initial data for the form.
  282. .. attribute:: form_class
  283. The form class to instantiate.
  284. .. attribute:: success_url
  285. The URL to redirect to when the form is successfully processed.
  286. .. method:: get_initial()
  287. Retrieve initial data for the form. By default, returns
  288. :attr:`.initial`.
  289. .. method:: get_form_class()
  290. Retrieve the form class to instantiate. By default
  291. :attr:`.form_class`.
  292. .. method:: get_form(form_class)
  293. Instantiate an instance of ``form_class`` using
  294. :meth:`.get_form_kwargs`.
  295. .. method:: get_form_kwargs()
  296. Build the keyword arguments required to instantiate the form.
  297. The ``initial`` argument is set to :meth:`.get_initial`. If the
  298. request is a ``POST`` or ``PUT``, the request data (``request.POST``
  299. and ``request.FILES``) will also be provided.
  300. .. method:: get_success_url()
  301. Determine the URL to redirect to when the form is successfully
  302. validated. Returns :attr:`.success_url` by default.
  303. .. method:: form_valid(form)
  304. Redirects to :meth:`.get_success_url`.
  305. .. method:: form_invalid(form)
  306. Renders a response, providing the invalid form as context.
  307. .. method:: get_context_data(**kwargs)
  308. Populates a context containing the contents of ``kwargs``.
  309. **Context**
  310. * ``form``: The form instance that was generated for the view.
  311. .. note::
  312. Views mixing :class:`FormMixin` must
  313. provide an implementation of :meth:`.form_valid` and
  314. :meth:`.form_invalid`.
  315. ModelFormMixin
  316. ~~~~~~~~~~~~~~
  317. .. class:: ModelFormMixin()
  318. A form mixin that works on ModelForms, rather than a standalone form.
  319. Since this is a subclass of
  320. :class:`~django.views.generic.detail.SingleObjectMixin`, instances of this
  321. mixin have access to the :attr:`~SingleObjectMixin.model` and
  322. :attr:`~SingleObjectMixin.queryset` attributes, describing the type of
  323. object that the ModelForm is manipulating. The view also provides
  324. ``self.object``, the instance being manipulated. If the instance is being
  325. created, ``self.object`` will be ``None``
  326. **Mixins**
  327. * :class:`django.views.generic.forms.FormMixin`
  328. * :class:`django.views.generic.detail.SingleObjectMixin`
  329. .. attribute:: success_url
  330. The URL to redirect to when the form is successfully processed.
  331. ``success_url`` may contain dictionary string formatting, which
  332. will be interpolated against the object's field attributes. For
  333. example, you could use ``success_url="/polls/%(slug)s/"`` to
  334. redirect to a URL composed out of the ``slug`` field on a model.
  335. .. method:: get_form_class()
  336. Retrieve the form class to instantiate. If
  337. :attr:`FormMixin.form_class` is provided, that class will be used.
  338. Otherwise, a ModelForm will be instantiated using the model associated
  339. with the :attr:`~SingleObjectMixin.queryset`, or with the
  340. :attr:`~SingleObjectMixin.model`, depending on which attribute is
  341. provided.
  342. .. method:: get_form_kwargs()
  343. Add the current instance (``self.object``) to the standard
  344. :meth:`FormMixin.get_form_kwargs`.
  345. .. method:: get_success_url()
  346. Determine the URL to redirect to when the form is successfully
  347. validated. Returns :attr:`FormMixin.success_url` if it is provided;
  348. otherwise, attempts to use the ``get_absolute_url()`` of the object.
  349. .. method:: form_valid()
  350. Saves the form instance, sets the current object for the view, and
  351. redirects to :meth:`.get_success_url`.
  352. .. method:: form_invalid()
  353. Renders a response, providing the invalid form as context.
  354. ProcessFormView
  355. ~~~~~~~~~~~~~~~
  356. .. class:: ProcessFormView()
  357. A mixin that provides basic HTTP GET and POST workflow.
  358. .. method:: get(request, *args, **kwargs)
  359. Constructs a form, then renders a response using a context that
  360. contains that form.
  361. .. method:: post(request, *args, **kwargs)
  362. Constructs a form, checks the form for validity, and handles it
  363. accordingly.
  364. The PUT action is also handled, as an analog of POST.
  365. DeletionMixin
  366. ~~~~~~~~~~~~~
  367. .. class:: DeletionMixin()
  368. Enables handling of the ``DELETE`` http action.
  369. .. attribute:: success_url
  370. The url to redirect to when the nominated object has been
  371. successfully deleted.
  372. .. method:: get_success_url(obj)
  373. Returns the url to redirect to when the nominated object has been
  374. successfully deleted. Returns
  375. :attr:`~django.views.generic.edit.DeletionMixin.success_url` by
  376. default.
  377. Date-based mixins
  378. -----------------
  379. .. currentmodule:: django.views.generic.dates
  380. YearMixin
  381. ~~~~~~~~~
  382. .. class:: YearMixin()
  383. A mixin that can be used to retrieve and provide parsing information for a
  384. year component of a date.
  385. .. attribute:: year_format
  386. The strftime_ format to use when parsing the year. By default, this is
  387. ``'%Y'``.
  388. .. _strftime: http://docs.python.org/library/time.html#time.strftime
  389. .. attribute:: year
  390. **Optional** The value for the year (as a string). By default, set to
  391. ``None``, which means the year will be determined using other means.
  392. .. method:: get_year_format()
  393. Returns the strftime_ format to use when parsing the year. Returns
  394. :attr:`YearMixin.year_format` by default.
  395. .. method:: get_year()
  396. Returns the year for which this view will display data. Tries the
  397. following sources, in order:
  398. * The value of the :attr:`YearMixin.year` attribute.
  399. * The value of the `year` argument captured in the URL pattern
  400. * The value of the `year` GET query argument.
  401. Raises a 404 if no valid year specification can be found.
  402. MonthMixin
  403. ~~~~~~~~~~
  404. .. class:: MonthMixin()
  405. A mixin that can be used to retrieve and provide parsing information for a
  406. month component of a date.
  407. .. attribute:: month_format
  408. The strftime_ format to use when parsing the month. By default, this is
  409. ``'%b'``.
  410. .. attribute:: month
  411. **Optional** The value for the month (as a string). By default, set to
  412. ``None``, which means the month will be determined using other means.
  413. .. method:: get_month_format()
  414. Returns the strftime_ format to use when parsing the month. Returns
  415. :attr:`MonthMixin.month_format` by default.
  416. .. method:: get_month()
  417. Returns the month for which this view will display data. Tries the
  418. following sources, in order:
  419. * The value of the :attr:`MonthMixin.month` attribute.
  420. * The value of the `month` argument captured in the URL pattern
  421. * The value of the `month` GET query argument.
  422. Raises a 404 if no valid month specification can be found.
  423. .. method:: get_next_month(date)
  424. Returns a date object containing the first day of the month after the
  425. date provided. Returns ``None`` if mixed with a view that sets
  426. ``allow_future = False``, and the next month is in the future. If
  427. ``allow_empty = False``, returns the next month that contains data.
  428. .. method:: get_prev_month(date)
  429. Returns a date object containing the first day of the month before the
  430. date provided. If ``allow_empty = False``, returns the previous month
  431. that contained data.
  432. DayMixin
  433. ~~~~~~~~~
  434. .. class:: DayMixin()
  435. A mixin that can be used to retrieve and provide parsing information for a
  436. day component of a date.
  437. .. attribute:: day_format
  438. The strftime_ format to use when parsing the day. By default, this is
  439. ``'%d'``.
  440. .. attribute:: day
  441. **Optional** The value for the day (as a string). By default, set to
  442. ``None``, which means the day will be determined using other means.
  443. .. method:: get_day_format()
  444. Returns the strftime_ format to use when parsing the day. Returns
  445. :attr:`DayMixin.day_format` by default.
  446. .. method:: get_day()
  447. Returns the day for which this view will display data. Tries the
  448. following sources, in order:
  449. * The value of the :attr:`DayMixin.day` attribute.
  450. * The value of the `day` argument captured in the URL pattern
  451. * The value of the `day` GET query argument.
  452. Raises a 404 if no valid day specification can be found.
  453. .. method:: get_next_day(date)
  454. Returns a date object containing the next day after the date provided.
  455. Returns ``None`` if mixed with a view that sets ``allow_future = False``,
  456. and the next day is in the future. If ``allow_empty = False``, returns
  457. the next day that contains data.
  458. .. method:: get_prev_day(date)
  459. Returns a date object containing the previous day. If
  460. ``allow_empty = False``, returns the previous day that contained data.
  461. WeekMixin
  462. ~~~~~~~~~
  463. .. class:: WeekMixin()
  464. A mixin that can be used to retrieve and provide parsing information for a
  465. week component of a date.
  466. .. attribute:: week_format
  467. The strftime_ format to use when parsing the week. By default, this is
  468. ``'%U'``.
  469. .. attribute:: week
  470. **Optional** The value for the week (as a string). By default, set to
  471. ``None``, which means the week will be determined using other means.
  472. .. method:: get_week_format()
  473. Returns the strftime_ format to use when parsing the week. Returns
  474. :attr:`WeekMixin.week_format` by default.
  475. .. method:: get_week()
  476. Returns the week for which this view will display data. Tries the
  477. following sources, in order:
  478. * The value of the :attr:`WeekMixin.week` attribute.
  479. * The value of the `week` argument captured in the URL pattern
  480. * The value of the `week` GET query argument.
  481. Raises a 404 if no valid week specification can be found.
  482. DateMixin
  483. ~~~~~~~~~
  484. .. class:: DateMixin()
  485. A mixin class providing common behavior for all date-based views.
  486. .. attribute:: date_field
  487. The name of the ``DateField`` or ``DateTimeField`` in the
  488. ``QuerySet``'s model that the date-based archive should use to
  489. determine the objects on the page.
  490. .. attribute:: allow_future
  491. A boolean specifying whether to include "future" objects on this page,
  492. where "future" means objects in which the field specified in
  493. ``date_field`` is greater than the current date/time. By default, this
  494. is ``False``.
  495. .. method:: get_date_field()
  496. Returns the name of the field that contains the date data that this
  497. view will operate on. Returns :attr:`DateMixin.date_field` by default.
  498. .. method:: get_allow_future()
  499. Determine whether to include "future" objects on this page, where
  500. "future" means objects in which the field specified in ``date_field``
  501. is greater than the current date/time. Returns
  502. :attr:`DateMixin.date_field` by default.
  503. BaseDateListView
  504. ~~~~~~~~~~~~~~~~
  505. .. class:: BaseDateListView()
  506. A base class that provides common behavior for all date-based views. There
  507. won't normally be a reason to instantiate
  508. :class:`~django.views.generic.dates.BaseDateListView`; instantiate one of
  509. the subclasses instead.
  510. While this view (and it's subclasses) are executing, ``self.object_list``
  511. will contain the list of objects that the view is operating upon, and
  512. ``self.date_list`` will contain the list of dates for which data is
  513. available.
  514. **Mixins**
  515. * :class:`~django.views.generic.dates.DateMixin`
  516. * :class:`~django.views.generic.list.MultipleObjectMixin`
  517. .. attribute:: allow_empty
  518. A boolean specifying whether to display the page if no objects are
  519. available. If this is ``False`` and no objects are available, the view
  520. will raise a 404 instead of displaying an empty page. By default, this
  521. is ``True``.
  522. .. method:: get_dated_items():
  523. Returns a 3-tuple containing (``date_list``, ``latest``,
  524. ``extra_context``).
  525. ``date_list`` is the list of dates for which data is available.
  526. ``object_list`` is the list of objects ``extra_context`` is a
  527. dictionary of context data that will be added to any context data
  528. provided by the
  529. :class:`~django.views.generic.list.MultipleObjectMixin`.
  530. .. method:: get_dated_queryset(**lookup)
  531. Returns a queryset, filtered using the query arguments defined by
  532. ``lookup``. Enforces any restrictions on the queryset, such as
  533. ``allow_empty`` and ``allow_future``.
  534. .. method:: get_date_list(queryset, date_type)
  535. Returns the list of dates of type ``date_type`` for which
  536. ``queryset`` contains entries. For example, ``get_date_list(qs,
  537. 'year')`` will return the list of years for which ``qs`` has entries.
  538. See :meth:`~django.db.models.QuerySet.dates()` for the
  539. ways that the ``date_type`` argument can be used.
  540. Generic views
  541. =============
  542. Simple generic views
  543. --------------------
  544. .. currentmodule:: django.views.generic.base
  545. View
  546. ~~~~
  547. .. class:: View()
  548. The master class-based base view. All other generic class-based views
  549. inherit from this base class.
  550. Each request served by a :class:`~django.views.generic.base.View` has an
  551. independent state; therefore, it is safe to store state variables on the
  552. instance (i.e., ``self.foo = 3`` is a thread-safe operation).
  553. A class-based view is deployed into a URL pattern using the
  554. :meth:`~View.as_view()` classmethod::
  555. urlpatterns = patterns('',
  556. (r'^view/$', MyView.as_view(size=42)),
  557. )
  558. Any argument passed into :meth:`~View.as_view()` will be assigned onto the
  559. instance that is used to service a request. Using the previous example,
  560. this means that every request on ``MyView`` is able to interrogate
  561. ``self.size``.
  562. .. admonition:: Thread safety with view arguments
  563. Arguments passed to a view are shared between every instance of a view.
  564. This means that you shoudn't use a list, dictionary, or any other
  565. variable object as an argument to a view. If you did, the actions of
  566. one user visiting your view could have an effect on subsequent users
  567. visiting the same view.
  568. .. method:: dispatch(request, *args, **kwargs)
  569. The ``view`` part of the view -- the method that accepts a ``request``
  570. argument plus arguments, and returns a HTTP response.
  571. The default implementation will inspect the HTTP method and attempt to
  572. delegate to a method that matches the HTTP method; a ``GET`` will be
  573. delegated to :meth:`~View.get()`, a ``POST`` to :meth:`~View.post()`,
  574. and so on.
  575. The default implementation also sets ``request``, ``args`` and
  576. ``kwargs`` as instance variables, so any method on the view can know
  577. the full details of the request that was made to invoke the view.
  578. .. method:: http_method_not_allowed(request, *args, **kwargs)
  579. If the view was called with HTTP method it doesn't support, this method
  580. is called instead.
  581. The default implementation returns ``HttpResponseNotAllowed`` with list
  582. of allowed methods in plain text.
  583. TemplateView
  584. ~~~~~~~~~~~~
  585. .. class:: TemplateView()
  586. Renders a given template, passing it a ``{{ params }}`` template variable,
  587. which is a dictionary of the parameters captured in the URL.
  588. **Mixins**
  589. * :class:`django.views.generic.base.TemplateResponseMixin`
  590. .. attribute:: template_name
  591. The full name of a template to use.
  592. .. method:: get_context_data(**kwargs)
  593. Return a context data dictionary consisting of the contents of
  594. ``kwargs`` stored in the context variable ``params``.
  595. **Context**
  596. * ``params``: The dictionary of keyword arguments captured from the URL
  597. pattern that served the view.
  598. RedirectView
  599. ~~~~~~~~~~~~
  600. .. class:: RedirectView()
  601. Redirects to a given URL.
  602. The given URL may contain dictionary-style string formatting, which will be
  603. interpolated against the parameters captured in the URL. Because keyword
  604. interpolation is *always* done (even if no arguments are passed in), any
  605. ``"%"`` characters in the URL must be written as ``"%%"`` so that Python
  606. will convert them to a single percent sign on output.
  607. If the given URL is ``None``, Django will return an ``HttpResponseGone``
  608. (410).
  609. .. attribute:: url
  610. The URL to redirect to, as a string. Or ``None`` to raise a 410 (Gone)
  611. HTTP error.
  612. .. attribute:: permanent
  613. Whether the redirect should be permanent. The only difference here is
  614. the HTTP status code returned. If ``True``, then the redirect will use
  615. status code 301. If ``False``, then the redirect will use status code
  616. 302. By default, ``permanent`` is ``True``.
  617. .. attribute:: query_string
  618. Whether to pass along the GET query string to the new location. If
  619. ``True``, then the query string is appended to the URL. If ``False``,
  620. then the query string is discarded. By default, ``query_string`` is
  621. ``False``.
  622. .. method:: get_redirect_url(**kwargs)
  623. Constructs the target URL for redirection.
  624. The default implementation uses :attr:`~RedirectView.url` as a starting
  625. string, performs expansion of ``%`` parameters in that string, as well
  626. as the appending of query string if requested by
  627. :attr:`~RedirectView.query_string`. Subclasses may implement any
  628. behavior they wish, as long as the method returns a redirect-ready URL
  629. string.
  630. Detail views
  631. ------------
  632. .. currentmodule:: django.views.generic.detail
  633. DetailView
  634. ~~~~~~~~~~
  635. .. class:: BaseDetailView()
  636. .. class:: DetailView()
  637. A page representing an individual object.
  638. While this view is executing, ``self.object`` will contain the object that
  639. the view is operating upon.
  640. :class:`~django.views.generic.base.BaseDetailView` implements the same
  641. behavior as :class:`~django.views.generic.base.DetailView`, but doesn't
  642. include the
  643. :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`.
  644. **Mixins**
  645. * :class:`django.views.generic.detail.SingleObjectMixin`
  646. * :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin`
  647. List views
  648. ----------
  649. .. currentmodule:: django.views.generic.list
  650. ListView
  651. ~~~~~~~~
  652. .. class:: BaseListView()
  653. .. class:: ListView()
  654. A page representing a list of objects.
  655. While this view is executing, ``self.object_list`` will contain the list of
  656. objects (usually, but not necessarily a queryset) that the view is
  657. operating upon.
  658. :class:`~django.views.generic.list.BaseListView` implements the same
  659. behavior as :class:`~django.views.generic.list.ListView`, but doesn't
  660. include the
  661. :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`.
  662. **Mixins**
  663. * :class:`django.views.generic.list.MultipleObjectMixin`
  664. * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
  665. Editing views
  666. -------------
  667. .. currentmodule:: django.views.generic.edit
  668. FormView
  669. ~~~~~~~~
  670. .. class:: BaseFormView()
  671. .. class:: FormView()
  672. A view that displays a form. On error, redisplays the form with validation
  673. errors; on success, redirects to a new URL.
  674. :class:`~django.views.generic.edit.BaseFormView` implements the same
  675. behavior as :class:`~django.views.generic.edit.FormView`, but doesn't
  676. include the :class:`~django.views.generic.base.TemplateResponseMixin`.
  677. **Mixins**
  678. * :class:`django.views.generic.edit.FormMixin`
  679. * :class:`django.views.generic.edit.ProcessFormView`
  680. CreateView
  681. ~~~~~~~~~~
  682. .. class:: BaseCreateView()
  683. .. class:: CreateView()
  684. A view that displays a form for creating an object, redisplaying the form
  685. with validation errors (if there are any) and saving the object.
  686. :class:`~django.views.generic.edit.BaseCreateView` implements the same
  687. behavior as :class:`~django.views.generic.edit.CreateView`, but doesn't
  688. include the :class:`~django.views.generic.base.TemplateResponseMixin`.
  689. **Mixins**
  690. * :class:`django.views.generic.edit.ModelFormMixin`
  691. * :class:`django.views.generic.edit.ProcessFormView`
  692. UpdateView
  693. ~~~~~~~~~~
  694. .. class:: BaseUpdateView()
  695. .. class:: UpdateView()
  696. A view that displays a form for editing an existing object, redisplaying
  697. the form with validation errors (if there are any) and saving changes to
  698. the object. This uses a form automatically generated from the object's
  699. model class (unless a form class is manually specified).
  700. :class:`~django.views.generic.edit.BaseUpdateView` implements the same
  701. behavior as :class:`~django.views.generic.edit.UpdateView`, but doesn't
  702. include the :class:`~django.views.generic.base.TemplateResponseMixin`.
  703. **Mixins**
  704. * :class:`django.views.generic.edit.ModelFormMixin`
  705. * :class:`django.views.generic.edit.ProcessFormView`
  706. DeleteView
  707. ~~~~~~~~~~
  708. .. class:: BaseDeleteView()
  709. .. class:: DeleteView()
  710. A view that displays a confirmation page and deletes an existing object.
  711. The given object will only be deleted if the request method is ``POST``. If
  712. this view is fetched via ``GET``, it will display a confirmation page that
  713. should contain a form that POSTs to the same URL.
  714. :class:`~django.views.generic.edit.BaseDeleteView` implements the same
  715. behavior as :class:`~django.views.generic.edit.DeleteView`, but doesn't
  716. include the :class:`~django.views.generic.base.TemplateResponseMixin`.
  717. **Mixins**
  718. * :class:`django.views.generic.edit.DeletionMixin`
  719. * :class:`django.views.generic.detail.BaseDetailView`
  720. **Notes**
  721. * The delete confirmation page displayed to a GET request uses a
  722. ``template_name_suffix`` of ``'_confirm_delete'``.
  723. Date-based views
  724. ----------------
  725. Date-based generic views (in the module :mod:`django.views.generic.dates`)
  726. are views for displaying drilldown pages for date-based data.
  727. .. currentmodule:: django.views.generic.dates
  728. ArchiveIndexView
  729. ~~~~~~~~~~~~~~~~
  730. .. class:: BaseArchiveIndexView()
  731. .. class:: ArchiveIndexView()
  732. A top-level index page showing the "latest" objects, by date. Objects with
  733. a date in the *future* are not included unless you set ``allow_future`` to
  734. ``True``.
  735. :class:`~django.views.generic.dates.BaseArchiveIndexView` implements the
  736. same behavior as :class:`~django.views.generic.dates.ArchiveIndexView`, but
  737. doesn't include the
  738. :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`.
  739. **Mixins**
  740. * :class:`django.views.generic.dates.BaseDateListView`
  741. * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
  742. **Notes**
  743. * Uses a default ``context_object_name`` of ``latest``.
  744. * Uses a default ``template_name_suffix`` of ``_archive``.
  745. YearArchiveView
  746. ~~~~~~~~~~~~~~~
  747. .. class:: BaseYearArchiveView()
  748. .. class:: YearArchiveView()
  749. A yearly archive page showing all available months in a given year. Objects
  750. with a date in the *future* are not displayed unless you set
  751. ``allow_future`` to ``True``.
  752. :class:`~django.views.generic.dates.BaseYearArchiveView` implements the
  753. same behavior as :class:`~django.views.generic.dates.YearArchiveView`, but
  754. doesn't include the
  755. :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`.
  756. **Mixins**
  757. * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
  758. * :class:`django.views.generic.dates.YearMixin`
  759. * :class:`django.views.generic.dates.BaseDateListView`
  760. .. attribute:: make_object_list
  761. A boolean specifying whether to retrieve the full list of objects for
  762. this year and pass those to the template. If ``True``, the list of
  763. objects will be made available to the context. By default, this is
  764. ``False``.
  765. .. method:: get_make_object_list()
  766. Determine if an object list will be returned as part of the context. If
  767. ``False``, the ``None`` queryset will be used as the object list.
  768. **Context**
  769. In addition to the context provided by
  770. :class:`django.views.generic.list.MultipleObjectMixin` (via
  771. :class:`django.views.generic.dates.BaseDateListView`), the template's
  772. context will be:
  773. * ``date_list``: A ``DateQuerySet`` object containing all months that
  774. have objects available according to ``queryset``, represented as
  775. ``datetime.datetime`` objects, in ascending order.
  776. * ``year``: The given year, as a four-character string.
  777. **Notes**
  778. * Uses a default ``template_name_suffix`` of ``_archive_year``.
  779. MonthArchiveView
  780. ~~~~~~~~~~~~~~~~
  781. .. class:: BaseMonthArchiveView()
  782. .. class:: MonthArchiveView()
  783. A monthly archive page showing all objects in a given month. Objects with a
  784. date in the *future* are not displayed unless you set ``allow_future`` to
  785. ``True``.
  786. :class:`~django.views.generic.dates.BaseMonthArchiveView` implements
  787. the same behavior as
  788. :class:`~django.views.generic.dates.MonthArchiveView`, but doesn't
  789. include the
  790. :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`.
  791. **Mixins**
  792. * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
  793. * :class:`django.views.generic.dates.YearMixin`
  794. * :class:`django.views.generic.dates.MonthMixin`
  795. * :class:`django.views.generic.dates.BaseDateListView`
  796. **Context**
  797. In addition to the context provided by
  798. :class:`~django.views.generic.list.MultipleObjectMixin` (via
  799. :class:`~django.views.generic.dates.BaseDateListView`), the template's
  800. context will be:
  801. * ``date_list``: A ``DateQuerySet`` object containing all days that
  802. have objects available in the given month, according to ``queryset``,
  803. represented as ``datetime.datetime`` objects, in ascending order.
  804. * ``month``: A ``datetime.date`` object representing the given month.
  805. * ``next_month``: A ``datetime.date`` object representing the first day
  806. of the next month. If the next month is in the future, this will be
  807. ``None``.
  808. * ``previous_month``: A ``datetime.date`` object representing the first
  809. day of the previous month. Unlike ``next_month``, this will never be
  810. ``None``.
  811. **Notes**
  812. * Uses a default ``template_name_suffix`` of ``_archive_month``.
  813. WeekArchiveView
  814. ~~~~~~~~~~~~~~~
  815. .. class:: BaseWeekArchiveView()
  816. .. class:: WeekArchiveView()
  817. A weekly archive page showing all objects in a given week. Objects with a
  818. date in the *future* are not displayed unless you set ``allow_future`` to
  819. ``True``.
  820. :class:`~django.views.generic.dates.BaseWeekArchiveView` implements the
  821. same behavior as :class:`~django.views.generic.dates.WeekArchiveView`, but
  822. doesn't include the
  823. :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`.
  824. **Mixins**
  825. * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
  826. * :class:`django.views.generic.dates.YearMixin`
  827. * :class:`django.views.generic.dates.MonthMixin`
  828. * :class:`django.views.generic.dates.BaseDateListView`
  829. **Context**
  830. In addition to the context provided by
  831. :class:`~django.views.generic.list.MultipleObjectMixin` (via
  832. :class:`~django.views.generic.dates.BaseDateListView`), the template's
  833. context will be:
  834. * ``week``: A ``datetime.date`` object representing the first day of
  835. the given week.
  836. **Notes**
  837. * Uses a default ``template_name_suffix`` of ``_archive_week``.
  838. DayArchiveView
  839. ~~~~~~~~~~~~~~
  840. .. class:: BaseDayArchiveView()
  841. .. class:: DayArchiveView()
  842. A day archive page showing all objects in a given day. Days in the future
  843. throw a 404 error, regardless of whether any objects exist for future days,
  844. unless you set ``allow_future`` to ``True``.
  845. :class:`~django.views.generic.dates.BaseDayArchiveView` implements the same
  846. behavior as :class:`~django.views.generic.dates.DayArchiveView`, but
  847. doesn't include the
  848. :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`.
  849. **Mixins**
  850. * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
  851. * :class:`django.views.generic.dates.YearMixin`
  852. * :class:`django.views.generic.dates.MonthMixin`
  853. * :class:`django.views.generic.dates.DayMixin`
  854. * :class:`django.views.generic.dates.BaseDateListView`
  855. **Context**
  856. In addition to the context provided by
  857. :class:`~django.views.generic.list.MultipleObjectMixin` (via
  858. :class:`~django.views.generic.dates.BaseDateListView`), the template's
  859. context will be:
  860. * ``day``: A ``datetime.date`` object representing the given day.
  861. * ``next_day``: A ``datetime.date`` object representing the next day.
  862. If the next day is in the future, this will be ``None``.
  863. * ``previous_day``: A ``datetime.date`` object representing the
  864. previous day. Unlike ``next_day``, this will never be ``None``.
  865. * ``next_month``: A ``datetime.date`` object representing the first day
  866. of the next month. If the next month is in the future, this will be
  867. ``None``.
  868. * ``previous_month``: A ``datetime.date`` object representing the first
  869. day of the previous month. Unlike ``next_month``, this will never be
  870. ``None``.
  871. **Notes**
  872. * Uses a default ``template_name_suffix`` of ``_archive_day``.
  873. TodayArchiveView
  874. ~~~~~~~~~~~~~~~~
  875. .. class:: BaseTodayArchiveView()
  876. .. class:: TodayArchiveView()
  877. A day archive page showing all objects for *today*. This is exactly the
  878. same as ``archive_day``, except the ``year``/``month``/``day`` arguments
  879. are not used,
  880. :class:`~django.views.generic.dates.BaseTodayArchiveView` implements the
  881. same behavior as :class:`~django.views.generic.dates.TodayArchiveView`, but
  882. doesn't include the
  883. :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`.
  884. **Mixins**
  885. * :class:`django.views.generic.dates.DayArchiveView`
  886. DateDetailView
  887. ~~~~~~~~~~~~~~
  888. .. class:: BaseDateDetailView()
  889. .. class:: DateDetailView()
  890. A page representing an individual object. If the object has a date value in
  891. the future, the view will throw a 404 error by default, unless you set
  892. ``allow_future`` to ``True``.
  893. :class:`~django.views.generic.dates.BaseDateDetailView` implements the same
  894. behavior as :class:`~django.views.generic.dates.DateDetailView`, but
  895. doesn't include the
  896. :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`.
  897. **Mixins**
  898. * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
  899. * :class:`django.views.generic.dates.YearMixin`
  900. * :class:`django.views.generic.dates.MonthMixin`
  901. * :class:`django.views.generic.dates.DayMixin`
  902. * :class:`django.views.generic.dates.BaseDateListView`