class-based-views.txt 46 KB

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