base.txt 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. ==========
  2. Base views
  3. ==========
  4. The following three classes provide much of the functionality needed to create
  5. Django views. You may think of them as *parent* views, which can be used by
  6. themselves or inherited from. They may not provide all the capabilities
  7. required for projects, in which case there are Mixins and Generic class-based
  8. views.
  9. Many of Django's built-in class-based views inherit from other class-based
  10. views or various mixins. Because this inheritance chain is very important, the
  11. ancestor classes are documented under the section title of **Ancestors (MRO)**.
  12. MRO is an acronym for Method Resolution Order.
  13. ``View``
  14. ========
  15. .. class:: django.views.generic.base.View
  16. The base view class. All other class-based views inherit from this base
  17. class. It isn't strictly a generic view and thus can also be imported from
  18. ``django.views``.
  19. **Method Flowchart**
  20. #. :meth:`setup()`
  21. #. :meth:`dispatch()`
  22. #. :meth:`http_method_not_allowed()`
  23. #. :meth:`options()`
  24. **Example views.py**::
  25. from django.http import HttpResponse
  26. from django.views import View
  27. class MyView(View):
  28. def get(self, request, *args, **kwargs):
  29. return HttpResponse('Hello, World!')
  30. **Example urls.py**::
  31. from django.urls import path
  32. from myapp.views import MyView
  33. urlpatterns = [
  34. path('mine/', MyView.as_view(), name='my-view'),
  35. ]
  36. **Attributes**
  37. .. attribute:: http_method_names
  38. The list of HTTP method names that this view will accept.
  39. Default::
  40. ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
  41. **Methods**
  42. .. classmethod:: as_view(**initkwargs)
  43. Returns a callable view that takes a request and returns a response::
  44. response = MyView.as_view()(request)
  45. The returned view has ``view_class`` and ``view_initkwargs``
  46. attributes.
  47. When the view is called during the request/response cycle, the
  48. :meth:`setup` method assigns the :class:`~django.http.HttpRequest` to
  49. the view's ``request`` attribute, and any positional and/or keyword
  50. arguments :ref:`captured from the URL pattern
  51. <how-django-processes-a-request>` to the ``args`` and ``kwargs``
  52. attributes, respectively. Then :meth:`dispatch` is called.
  53. If a ``View`` subclass defines asynchronous (``async def``) method
  54. handlers, ``as_view()`` will mark the returned callable as a coroutine
  55. function. An ``ImproperlyConfigured`` exception will be raised if both
  56. asynchronous (``async def``) and synchronous (``def``) handlers are
  57. defined on a single view-class.
  58. .. versionchanged:: 4.1
  59. Compatibility with asynchronous (``async def``) method handlers was
  60. added.
  61. .. method:: setup(request, *args, **kwargs)
  62. Performs key view initialization prior to :meth:`dispatch`.
  63. If overriding this method, you must call ``super()``.
  64. .. method:: dispatch(request, *args, **kwargs)
  65. The ``view`` part of the view -- the method that accepts a ``request``
  66. argument plus arguments, and returns an HTTP response.
  67. The default implementation will inspect the HTTP method and attempt to
  68. delegate to a method that matches the HTTP method; a ``GET`` will be
  69. delegated to ``get()``, a ``POST`` to ``post()``, and so on.
  70. By default, a ``HEAD`` request will be delegated to ``get()``.
  71. If you need to handle ``HEAD`` requests in a different way than ``GET``,
  72. you can override the ``head()`` method. See
  73. :ref:`supporting-other-http-methods` for an example.
  74. .. method:: http_method_not_allowed(request, *args, **kwargs)
  75. If the view was called with an HTTP method it doesn't support, this
  76. method is called instead.
  77. The default implementation returns ``HttpResponseNotAllowed`` with a
  78. list of allowed methods in plain text.
  79. .. method:: options(request, *args, **kwargs)
  80. Handles responding to requests for the OPTIONS HTTP verb. Returns a
  81. response with the ``Allow`` header containing a list of the view's
  82. allowed HTTP method names.
  83. If the other HTTP methods handlers on the class are asynchronous
  84. (``async def``) then the response will be wrapped in a coroutine
  85. function for use with ``await``.
  86. .. versionchanged:: 4.1
  87. Compatibility with classes defining asynchronous (``async def``)
  88. method handlers was added.
  89. ``TemplateView``
  90. ================
  91. .. class:: django.views.generic.base.TemplateView
  92. Renders a given template, with the context containing parameters captured
  93. in the URL.
  94. **Ancestors (MRO)**
  95. This view inherits methods and attributes from the following views:
  96. * :class:`django.views.generic.base.TemplateResponseMixin`
  97. * :class:`django.views.generic.base.ContextMixin`
  98. * :class:`django.views.generic.base.View`
  99. **Method Flowchart**
  100. #. :meth:`~django.views.generic.base.View.setup()`
  101. #. :meth:`~django.views.generic.base.View.dispatch()`
  102. #. :meth:`~django.views.generic.base.View.http_method_not_allowed()`
  103. #. :meth:`~django.views.generic.base.ContextMixin.get_context_data()`
  104. **Example views.py**::
  105. from django.views.generic.base import TemplateView
  106. from articles.models import Article
  107. class HomePageView(TemplateView):
  108. template_name = "home.html"
  109. def get_context_data(self, **kwargs):
  110. context = super().get_context_data(**kwargs)
  111. context['latest_articles'] = Article.objects.all()[:5]
  112. return context
  113. **Example urls.py**::
  114. from django.urls import path
  115. from myapp.views import HomePageView
  116. urlpatterns = [
  117. path('', HomePageView.as_view(), name='home'),
  118. ]
  119. **Context**
  120. * Populated (through :class:`~django.views.generic.base.ContextMixin`) with
  121. the keyword arguments captured from the URL pattern that served the view.
  122. * You can also add context using the
  123. :attr:`~django.views.generic.base.ContextMixin.extra_context` keyword
  124. argument for :meth:`~django.views.generic.base.View.as_view`.
  125. ``RedirectView``
  126. ================
  127. .. class:: django.views.generic.base.RedirectView
  128. Redirects to a given URL.
  129. The given URL may contain dictionary-style string formatting, which will be
  130. interpolated against the parameters captured in the URL. Because keyword
  131. interpolation is *always* done (even if no arguments are passed in), any
  132. ``"%"`` characters in the URL must be written as ``"%%"`` so that Python
  133. will convert them to a single percent sign on output.
  134. If the given URL is ``None``, Django will return an ``HttpResponseGone``
  135. (410).
  136. **Ancestors (MRO)**
  137. This view inherits methods and attributes from the following view:
  138. * :class:`django.views.generic.base.View`
  139. **Method Flowchart**
  140. #. :meth:`~django.views.generic.base.View.setup()`
  141. #. :meth:`~django.views.generic.base.View.dispatch()`
  142. #. :meth:`~django.views.generic.base.View.http_method_not_allowed()`
  143. #. :meth:`get_redirect_url()`
  144. **Example views.py**::
  145. from django.shortcuts import get_object_or_404
  146. from django.views.generic.base import RedirectView
  147. from articles.models import Article
  148. class ArticleCounterRedirectView(RedirectView):
  149. permanent = False
  150. query_string = True
  151. pattern_name = 'article-detail'
  152. def get_redirect_url(self, *args, **kwargs):
  153. article = get_object_or_404(Article, pk=kwargs['pk'])
  154. article.update_counter()
  155. return super().get_redirect_url(*args, **kwargs)
  156. **Example urls.py**::
  157. from django.urls import path
  158. from django.views.generic.base import RedirectView
  159. from article.views import ArticleCounterRedirectView, ArticleDetailView
  160. urlpatterns = [
  161. path('counter/<int:pk>/', ArticleCounterRedirectView.as_view(), name='article-counter'),
  162. path('details/<int:pk>/', ArticleDetailView.as_view(), name='article-detail'),
  163. path('go-to-django/', RedirectView.as_view(url='https://www.djangoproject.com/'), name='go-to-django'),
  164. ]
  165. **Attributes**
  166. .. attribute:: url
  167. The URL to redirect to, as a string. Or ``None`` to raise a 410 (Gone)
  168. HTTP error.
  169. .. attribute:: pattern_name
  170. The name of the URL pattern to redirect to. Reversing will be done
  171. using the same args and kwargs as are passed in for this view.
  172. .. attribute:: permanent
  173. Whether the redirect should be permanent. The only difference here is
  174. the HTTP status code returned. If ``True``, then the redirect will use
  175. status code 301. If ``False``, then the redirect will use status code
  176. 302. By default, ``permanent`` is ``False``.
  177. .. attribute:: query_string
  178. Whether to pass along the GET query string to the new location. If
  179. ``True``, then the query string is appended to the URL. If ``False``,
  180. then the query string is discarded. By default, ``query_string`` is
  181. ``False``.
  182. **Methods**
  183. .. method:: get_redirect_url(*args, **kwargs)
  184. Constructs the target URL for redirection.
  185. The ``args`` and ``kwargs`` arguments are positional and/or keyword
  186. arguments :ref:`captured from the URL pattern
  187. <how-django-processes-a-request>`, respectively.
  188. The default implementation uses :attr:`url` as a starting
  189. string and performs expansion of ``%`` named parameters in that string
  190. using the named groups captured in the URL.
  191. If :attr:`url` is not set, ``get_redirect_url()`` tries to reverse the
  192. :attr:`pattern_name` using what was captured in the URL (both named and
  193. unnamed groups are used).
  194. If requested by :attr:`query_string`, it will also append the query
  195. string to the generated URL.
  196. Subclasses may implement any behavior they wish, as long as the method
  197. returns a redirect-ready URL string.