class-based-views.txt 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338
  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:: slug_url_kwarg
  99. .. versionadded:: 1.4
  100. The name of the URLConf keyword argument that contains the slug. By
  101. default, ``slug_url_kwarg`` is ``'slug'``.
  102. .. attribute:: pk_url_kwarg
  103. .. versionadded:: 1.4
  104. The name of the URLConf keyword argument that contains the primary key.
  105. By default, ``pk_url_kwarg`` is ``'pk'``.
  106. .. attribute:: context_object_name
  107. Designates the name of the variable to use in the context.
  108. .. method:: get_object(queryset=None)
  109. Returns the single object that this view will display. If
  110. ``queryset`` is provided, that queryset will be used as the
  111. source of objects; otherwise,
  112. :meth:`~SingleObjectMixin.get_queryset` will be used.
  113. ``get_object()`` looks for a
  114. :attr:`SingleObjectMixin.pk_url_kwarg` argument in the arguments
  115. to the view; if this argument is found, this method performs a
  116. primary-key based lookup using that value. If this argument is not
  117. found, it looks for a :attr:`SingleObjectMixin.slug_url_kwarg`
  118. argument, and performs a slug lookup using the
  119. :attr:`SingleObjectMixin.slug_field`.
  120. .. method:: get_queryset()
  121. Returns the queryset that will be used to retrieve the object that
  122. this view will display. By default,
  123. :meth:`~SingleObjectMixin.get_queryset` returns the value of the
  124. :attr:`~SingleObjectMixin.queryset` attribute if it is set, otherwise
  125. it constructs a :class:`QuerySet` by calling the `all()` method on the
  126. :attr:`~SingleObjectMixin.model` attribute's default manager.
  127. .. method:: get_context_object_name(obj)
  128. Return the context variable name that will be used to contain the
  129. data that this view is manipulating. If
  130. :attr:`~SingleObjectMixin.context_object_name` is not set, the context
  131. name will be constructed from the ``object_name`` of the model that
  132. the queryset is composed from. For example, the model ``Article``
  133. would have context object named ``'article'``.
  134. .. method:: get_context_data(**kwargs)
  135. Returns context data for displaying the list of objects.
  136. **Context**
  137. * ``object``: The object that this view is displaying. If
  138. ``context_object_name`` is specified, that variable will also be
  139. set in the context, with the same value as ``object``.
  140. SingleObjectTemplateResponseMixin
  141. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  142. .. class:: SingleObjectTemplateResponseMixin()
  143. A mixin class that performs template-based response rendering for views
  144. that operate upon a single object instance. Requires that the view it is
  145. mixed with provides ``self.object``, the object instance that the view is
  146. operating on. ``self.object`` will usually be, but is not required to be,
  147. an instance of a Django model. It may be ``None`` if the view is in the
  148. process of constructing a new instance.
  149. **Extends**
  150. * :class:`~django.views.generic.base.TemplateResponseMixin`
  151. .. attribute:: template_name_field
  152. The field on the current object instance that can be used to determine
  153. the name of a candidate template. If either ``template_name_field`` or
  154. the value of the ``template_name_field`` on the current object instance
  155. is ``None``, the object will not be interrogated for a candidate
  156. template name.
  157. .. attribute:: template_name_suffix
  158. The suffix to append to the auto-generated candidate template name.
  159. Default suffix is ``_detail``.
  160. .. method:: get_template_names()
  161. Returns a list of candidate template names. Returns the following list:
  162. * the value of ``template_name`` on the view (if provided)
  163. * the contents of the ``template_name_field`` field on the
  164. object instance that the view is operating upon (if available)
  165. * ``<app_label>/<object_name><template_name_suffix>.html``
  166. Multiple object mixins
  167. ----------------------
  168. .. currentmodule:: django.views.generic.list
  169. MultipleObjectMixin
  170. ~~~~~~~~~~~~~~~~~~~
  171. .. class:: MultipleObjectMixin()
  172. A mixin that can be used to display a list of objects.
  173. If ``paginate_by`` is specified, Django will paginate the results returned
  174. by this. You can specify the page number in the URL in one of two ways:
  175. * Use the ``page`` parameter in the URLconf. For example, this is what
  176. your URLconf might look like::
  177. (r'^objects/page(?P<page>[0-9]+)/$', PaginatedView.as_view())
  178. * Pass the page number via the ``page`` query-string parameter. For
  179. example, a URL would look like this::
  180. /objects/?page=3
  181. These values and lists are 1-based, not 0-based, so the first page would be
  182. represented as page ``1``.
  183. For more on pagination, read the :doc:`pagination documentation
  184. </topics/pagination>`.
  185. As a special case, you are also permitted to use ``last`` as a value for
  186. ``page``::
  187. /objects/?page=last
  188. This allows you to access the final page of results without first having to
  189. determine how many pages there are.
  190. Note that ``page`` *must* be either a valid page number or the value
  191. ``last``; any other value for ``page`` will result in a 404 error.
  192. .. attribute:: allow_empty
  193. A boolean specifying whether to display the page if no objects are
  194. available. If this is ``False`` and no objects are available, the view
  195. will raise a 404 instead of displaying an empty page. By default, this
  196. is ``True``.
  197. .. attribute:: model
  198. The model that this view will display data for. Specifying ``model
  199. = Foo`` is effectively the same as specifying ``queryset =
  200. Foo.objects.all()``.
  201. .. attribute:: queryset
  202. A ``QuerySet`` that represents the objects. If provided, the value of
  203. :attr:`MultipleObjectMixin.queryset` supersedes the value provided for
  204. :attr:`MultipleObjectMixin.model`.
  205. .. attribute:: paginate_by
  206. An integer specifying how many objects should be displayed per page. If
  207. this is given, the view will paginate objects with
  208. :attr:`MultipleObjectMixin.paginate_by` objects per page. The view will
  209. expect either a ``page`` query string parameter (via ``GET``) or a
  210. ``page`` variable specified in the URLconf.
  211. .. attribute:: paginator_class
  212. The paginator class to be used for pagination. By default,
  213. :class:`django.core.paginator.Paginator` is used. If the custom paginator
  214. class doesn't have the same constructor interface as
  215. :class:`django.core.paginator.Paginator`, you will also need to
  216. provide an implementation for :meth:`MultipleObjectMixin.get_paginator`.
  217. .. attribute:: context_object_name
  218. Designates the name of the variable to use in the context.
  219. .. method:: get_queryset()
  220. Returns the queryset that represents the data this view will display.
  221. .. method:: paginate_queryset(queryset, page_size)
  222. Returns a 4-tuple containing (``paginator``, ``page``, ``object_list``,
  223. ``is_paginated``).
  224. Constructed by paginating ``queryset`` into pages of size ``page_size``.
  225. If the request contains a ``page`` argument, either as a captured URL
  226. argument or as a GET argument, ``object_list`` will correspond to the
  227. objects from that page.
  228. .. method:: get_paginate_by(queryset)
  229. Returns the number of items to paginate by, or ``None`` for no
  230. pagination. By default this simply returns the value of
  231. :attr:`MultipleObjectMixin.paginate_by`.
  232. .. method:: get_paginator(queryset, per_page, orphans=0, allow_empty_first_page=True)
  233. Returns an instance of the paginator to use for this view. By default,
  234. instantiates an instance of :attr:`paginator_class`.
  235. .. method:: get_allow_empty()
  236. Return a boolean specifying whether to display the page if no objects
  237. are available. If this method returns ``False`` and no objects are
  238. available, the view will raise a 404 instead of displaying an empty
  239. page. By default, this is ``True``.
  240. .. method:: get_context_object_name(object_list)
  241. Return the context variable name that will be used to contain
  242. the list of data that this view is manipulating. If
  243. ``object_list`` is a queryset of Django objects and
  244. :attr:`~MultipleObjectMixin.context_object_name` is not set,
  245. the context name will be the ``object_name`` of the model that
  246. the queryset is composed from, with postfix ``'_list'``
  247. appended. For example, the model ``Article`` would have a
  248. context object named ``article_list``.
  249. .. method:: get_context_data(**kwargs)
  250. Returns context data for displaying the list of objects.
  251. **Context**
  252. * ``object_list``: The list of objects that this view is displaying. If
  253. ``context_object_name`` is specified, that variable will also be set
  254. in the context, with the same value as ``object_list``.
  255. * ``is_paginated``: A boolean representing whether the results are
  256. paginated. Specifically, this is set to ``False`` if no page size has
  257. been specified, or if the available objects do not span multiple
  258. pages.
  259. * ``paginator``: An instance of
  260. :class:`django.core.paginator.Paginator`. If the page is not
  261. paginated, this context variable will be ``None``.
  262. * ``page_obj``: An instance of
  263. :class:`django.core.paginator.Page`. If the page is not paginated,
  264. this context variable will be ``None``.
  265. MultipleObjectTemplateResponseMixin
  266. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  267. .. class:: MultipleObjectTemplateResponseMixin()
  268. A mixin class that performs template-based response rendering for views
  269. that operate upon a list of object instances. Requires that the view it is
  270. mixed with provides ``self.object_list``, the list of object instances that
  271. the view is operating on. ``self.object_list`` may be, but is not required
  272. to be, a :class:`~django.db.models.query.QuerySet`.
  273. **Extends**
  274. * :class:`~django.views.generic.base.TemplateResponseMixin`
  275. .. attribute:: template_name_suffix
  276. The suffix to append to the auto-generated candidate template name.
  277. Default suffix is ``_list``.
  278. .. method:: get_template_names()
  279. Returns a list of candidate template names. Returns the following list:
  280. * the value of ``template_name`` on the view (if provided)
  281. * ``<app_label>/<object_name><template_name_suffix>.html``
  282. Editing mixins
  283. --------------
  284. .. currentmodule:: django.views.generic.edit
  285. FormMixin
  286. ~~~~~~~~~
  287. .. class:: FormMixin()
  288. A mixin class that provides facilities for creating and displaying forms.
  289. .. attribute:: initial
  290. A dictionary containing initial data for the form.
  291. .. attribute:: form_class
  292. The form class to instantiate.
  293. .. attribute:: success_url
  294. The URL to redirect to when the form is successfully processed.
  295. .. method:: get_initial()
  296. Retrieve initial data for the form. By default, returns
  297. :attr:`.initial`.
  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`