2
0

base.txt 9.9 KB

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