base.txt 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. .. method:: setup(request, *args, **kwargs)
  59. Performs key view initialization prior to :meth:`dispatch`.
  60. Assigns the :class:`~django.http.HttpRequest` to the view's ``request``
  61. attribute, and any positional and/or keyword arguments
  62. :ref:`captured from the URL pattern <how-django-processes-a-request>`
  63. to the ``args`` and ``kwargs`` attributes, respectively.
  64. If overriding this method, you must call ``super()``.
  65. .. method:: dispatch(request, *args, **kwargs)
  66. The ``view`` part of the view -- the method that accepts a ``request``
  67. argument plus arguments, and returns an HTTP response.
  68. The default implementation will inspect the HTTP method and attempt to
  69. delegate to a method that matches the HTTP method; a ``GET`` will be
  70. delegated to ``get()``, a ``POST`` to ``post()``, and so on.
  71. By default, a ``HEAD`` request will be delegated to ``get()``.
  72. If you need to handle ``HEAD`` requests in a different way than ``GET``,
  73. you can override the ``head()`` method. See
  74. :ref:`supporting-other-http-methods` for an example.
  75. .. method:: http_method_not_allowed(request, *args, **kwargs)
  76. If the view was called with an HTTP method it doesn't support, this
  77. method is called instead.
  78. The default implementation returns ``HttpResponseNotAllowed`` with a
  79. list of allowed methods in plain text.
  80. .. method:: options(request, *args, **kwargs)
  81. Handles responding to requests for the OPTIONS HTTP verb. Returns a
  82. response with the ``Allow`` header containing a list of the view's
  83. allowed HTTP method names.
  84. If the other HTTP methods handlers on the class are asynchronous
  85. (``async def``) then the response will be wrapped in a coroutine
  86. function for use with ``await``.
  87. ``TemplateView``
  88. ================
  89. .. class:: django.views.generic.base.TemplateView
  90. Renders a given template, with the context containing parameters captured
  91. in the URL.
  92. **Ancestors (MRO)**
  93. This view inherits methods and attributes from the following views:
  94. * :class:`django.views.generic.base.TemplateResponseMixin`
  95. * :class:`django.views.generic.base.ContextMixin`
  96. * :class:`django.views.generic.base.View`
  97. **Method Flowchart**
  98. #. :meth:`~django.views.generic.base.View.setup()`
  99. #. :meth:`~django.views.generic.base.View.dispatch()`
  100. #. :meth:`~django.views.generic.base.View.http_method_not_allowed()`
  101. #. :meth:`~django.views.generic.base.ContextMixin.get_context_data()`
  102. **Example views.py**::
  103. from django.views.generic.base import TemplateView
  104. from articles.models import Article
  105. class HomePageView(TemplateView):
  106. template_name = "home.html"
  107. def get_context_data(self, **kwargs):
  108. context = super().get_context_data(**kwargs)
  109. context["latest_articles"] = Article.objects.all()[:5]
  110. return context
  111. **Example urls.py**::
  112. from django.urls import path
  113. from myapp.views import HomePageView
  114. urlpatterns = [
  115. path("", HomePageView.as_view(), name="home"),
  116. ]
  117. **Context**
  118. * Populated (through :class:`~django.views.generic.base.ContextMixin`) with
  119. the keyword arguments captured from the URL pattern that served the view.
  120. * You can also add context using the
  121. :attr:`~django.views.generic.base.ContextMixin.extra_context` keyword
  122. argument for :meth:`~django.views.generic.base.View.as_view`.
  123. ``RedirectView``
  124. ================
  125. .. class:: django.views.generic.base.RedirectView
  126. Redirects to a given URL.
  127. The given URL may contain dictionary-style string formatting, which will be
  128. interpolated against the parameters captured in the URL. Because keyword
  129. interpolation is *always* done (even if no arguments are passed in), any
  130. ``"%"`` characters in the URL must be written as ``"%%"`` so that Python
  131. will convert them to a single percent sign on output.
  132. If the given URL is ``None``, Django will return an ``HttpResponseGone``
  133. (410).
  134. **Ancestors (MRO)**
  135. This view inherits methods and attributes from the following view:
  136. * :class:`django.views.generic.base.View`
  137. **Method Flowchart**
  138. #. :meth:`~django.views.generic.base.View.setup()`
  139. #. :meth:`~django.views.generic.base.View.dispatch()`
  140. #. :meth:`~django.views.generic.base.View.http_method_not_allowed()`
  141. #. :meth:`get_redirect_url()`
  142. **Example views.py**::
  143. from django.shortcuts import get_object_or_404
  144. from django.views.generic.base import RedirectView
  145. from articles.models import Article
  146. class ArticleCounterRedirectView(RedirectView):
  147. permanent = False
  148. query_string = True
  149. pattern_name = "article-detail"
  150. def get_redirect_url(self, *args, **kwargs):
  151. article = get_object_or_404(Article, pk=kwargs["pk"])
  152. article.update_counter()
  153. return super().get_redirect_url(*args, **kwargs)
  154. **Example urls.py**::
  155. from django.urls import path
  156. from django.views.generic.base import RedirectView
  157. from article.views import ArticleCounterRedirectView, ArticleDetailView
  158. urlpatterns = [
  159. path(
  160. "counter/<int:pk>/",
  161. ArticleCounterRedirectView.as_view(),
  162. name="article-counter",
  163. ),
  164. path("details/<int:pk>/", ArticleDetailView.as_view(), name="article-detail"),
  165. path(
  166. "go-to-django/",
  167. RedirectView.as_view(url="https://www.djangoproject.com/"),
  168. name="go-to-django",
  169. ),
  170. ]
  171. **Attributes**
  172. .. attribute:: url
  173. The URL to redirect to, as a string. Or ``None`` to raise a 410 (Gone)
  174. HTTP error.
  175. .. attribute:: pattern_name
  176. The name of the URL pattern to redirect to. Reversing will be done
  177. using the same args and kwargs as are passed in for this view.
  178. .. attribute:: permanent
  179. Whether the redirect should be permanent. The only difference here is
  180. the HTTP status code returned. If ``True``, then the redirect will use
  181. status code 301. If ``False``, then the redirect will use status code
  182. 302. By default, ``permanent`` is ``False``.
  183. .. attribute:: query_string
  184. Whether to pass along the GET query string to the new location. If
  185. ``True``, then the query string is appended to the URL. If ``False``,
  186. then the query string is discarded. By default, ``query_string`` is
  187. ``False``.
  188. **Methods**
  189. .. method:: get_redirect_url(*args, **kwargs)
  190. Constructs the target URL for redirection.
  191. The ``args`` and ``kwargs`` arguments are positional and/or keyword
  192. arguments :ref:`captured from the URL pattern
  193. <how-django-processes-a-request>`, respectively.
  194. The default implementation uses :attr:`url` as a starting
  195. string and performs expansion of ``%`` named parameters in that string
  196. using the named groups captured in the URL.
  197. If :attr:`url` is not set, ``get_redirect_url()`` tries to reverse the
  198. :attr:`pattern_name` using what was captured in the URL (both named and
  199. unnamed groups are used).
  200. If requested by :attr:`query_string`, it will also append the query
  201. string to the generated URL.
  202. Subclasses may implement any behavior they wish, as long as the method
  203. returns a redirect-ready URL string.