base.txt 9.1 KB

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