class-based-views.txt 46 KB

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