base.txt 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. 1. :meth:`dispatch()`
  21. 2. :meth:`http_method_not_allowed()`
  22. 3. :meth:`options()`
  23. **Example views.py**::
  24. from django.http import HttpResponse
  25. from django.views import View
  26. class MyView(View):
  27. def get(self, request, *args, **kwargs):
  28. return HttpResponse('Hello, World!')
  29. **Example urls.py**::
  30. from django.conf.urls import url
  31. from myapp.views import MyView
  32. urlpatterns = [
  33. url(r'^mine/$', MyView.as_view(), name='my-view'),
  34. ]
  35. **Attributes**
  36. .. attribute:: http_method_names
  37. The list of HTTP method names that this view will accept.
  38. Default::
  39. ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
  40. **Methods**
  41. .. classmethod:: as_view(**initkwargs)
  42. Returns a callable view that takes a request and returns a response::
  43. response = MyView.as_view()(request)
  44. The returned view has ``view_class`` and ``view_initkwargs``
  45. attributes.
  46. When the view is called during the request/response cycle, the
  47. :class:`~django.http.HttpRequest` is assigned to the view's ``request``
  48. attribute. Any positional and/or keyword arguments :ref:`captured from
  49. the URL pattern <how-django-processes-a-request>` are assigned to the
  50. ``args`` and ``kwargs`` attributes, respectively. Then :meth:`dispatch`
  51. is called.
  52. .. method:: dispatch(request, *args, **kwargs)
  53. The ``view`` part of the view -- the method that accepts a ``request``
  54. argument plus arguments, and returns a HTTP response.
  55. The default implementation will inspect the HTTP method and attempt to
  56. delegate to a method that matches the HTTP method; a ``GET`` will be
  57. delegated to ``get()``, a ``POST`` to ``post()``, and so on.
  58. By default, a ``HEAD`` request will be delegated to ``get()``.
  59. If you need to handle ``HEAD`` requests in a different way than ``GET``,
  60. you can override the ``head()`` method. See
  61. :ref:`supporting-other-http-methods` for an example.
  62. .. method:: http_method_not_allowed(request, *args, **kwargs)
  63. If the view was called with a HTTP method it doesn't support, this
  64. method is called instead.
  65. The default implementation returns ``HttpResponseNotAllowed`` with a
  66. list of allowed methods in plain text.
  67. .. method:: options(request, *args, **kwargs)
  68. Handles responding to requests for the OPTIONS HTTP verb. Returns a
  69. response with the ``Allow`` header containing a list of the view's
  70. allowed HTTP method names.
  71. ``TemplateView``
  72. ================
  73. .. class:: django.views.generic.base.TemplateView
  74. Renders a given template, with the context containing parameters captured
  75. in the URL.
  76. **Ancestors (MRO)**
  77. This view inherits methods and attributes from the following views:
  78. * :class:`django.views.generic.base.TemplateResponseMixin`
  79. * :class:`django.views.generic.base.ContextMixin`
  80. * :class:`django.views.generic.base.View`
  81. **Method Flowchart**
  82. 1. :meth:`~django.views.generic.base.View.dispatch()`
  83. 2. :meth:`~django.views.generic.base.View.http_method_not_allowed()`
  84. 3. :meth:`~django.views.generic.base.ContextMixin.get_context_data()`
  85. **Example views.py**::
  86. from django.views.generic.base import TemplateView
  87. from articles.models import Article
  88. class HomePageView(TemplateView):
  89. template_name = "home.html"
  90. def get_context_data(self, **kwargs):
  91. context = super().get_context_data(**kwargs)
  92. context['latest_articles'] = Article.objects.all()[:5]
  93. return context
  94. **Example urls.py**::
  95. from django.conf.urls import url
  96. from myapp.views import HomePageView
  97. urlpatterns = [
  98. url(r'^$', HomePageView.as_view(), name='home'),
  99. ]
  100. **Context**
  101. * Populated (through :class:`~django.views.generic.base.ContextMixin`) with
  102. the keyword arguments captured from the URL pattern that served the view.
  103. * You can also add context using the
  104. :attr:`~django.views.generic.base.ContextMixin.extra_context` keyword
  105. argument for :meth:`~django.views.generic.base.View.as_view`.
  106. ``RedirectView``
  107. ================
  108. .. class:: django.views.generic.base.RedirectView
  109. Redirects to a given URL.
  110. The given URL may contain dictionary-style string formatting, which will be
  111. interpolated against the parameters captured in the URL. Because keyword
  112. interpolation is *always* done (even if no arguments are passed in), any
  113. ``"%"`` characters in the URL must be written as ``"%%"`` so that Python
  114. will convert them to a single percent sign on output.
  115. If the given URL is ``None``, Django will return an ``HttpResponseGone``
  116. (410).
  117. **Ancestors (MRO)**
  118. This view inherits methods and attributes from the following view:
  119. * :class:`django.views.generic.base.View`
  120. **Method Flowchart**
  121. 1. :meth:`~django.views.generic.base.View.dispatch()`
  122. 2. :meth:`~django.views.generic.base.View.http_method_not_allowed()`
  123. 3. :meth:`get_redirect_url()`
  124. **Example views.py**::
  125. from django.shortcuts import get_object_or_404
  126. from django.views.generic.base import RedirectView
  127. from articles.models import Article
  128. class ArticleCounterRedirectView(RedirectView):
  129. permanent = False
  130. query_string = True
  131. pattern_name = 'article-detail'
  132. def get_redirect_url(self, *args, **kwargs):
  133. article = get_object_or_404(Article, pk=kwargs['pk'])
  134. article.update_counter()
  135. return super().get_redirect_url(*args, **kwargs)
  136. **Example urls.py**::
  137. from django.conf.urls import url
  138. from django.views.generic.base import RedirectView
  139. from article.views import ArticleCounterRedirectView, ArticleDetail
  140. urlpatterns = [
  141. url(r'^counter/(?P<pk>[0-9]+)/$', ArticleCounterRedirectView.as_view(), name='article-counter'),
  142. url(r'^details/(?P<pk>[0-9]+)/$', ArticleDetail.as_view(), name='article-detail'),
  143. url(r'^go-to-django/$', RedirectView.as_view(url='https://djangoproject.com'), name='go-to-django'),
  144. ]
  145. **Attributes**
  146. .. attribute:: url
  147. The URL to redirect to, as a string. Or ``None`` to raise a 410 (Gone)
  148. HTTP error.
  149. .. attribute:: pattern_name
  150. The name of the URL pattern to redirect to. Reversing will be done
  151. using the same args and kwargs as are passed in for this view.
  152. .. attribute:: permanent
  153. Whether the redirect should be permanent. The only difference here is
  154. the HTTP status code returned. If ``True``, then the redirect will use
  155. status code 301. If ``False``, then the redirect will use status code
  156. 302. By default, ``permanent`` is ``False``.
  157. .. attribute:: query_string
  158. Whether to pass along the GET query string to the new location. If
  159. ``True``, then the query string is appended to the URL. If ``False``,
  160. then the query string is discarded. By default, ``query_string`` is
  161. ``False``.
  162. **Methods**
  163. .. method:: get_redirect_url(*args, **kwargs)
  164. Constructs the target URL for redirection.
  165. The default implementation uses :attr:`url` as a starting
  166. string and performs expansion of ``%`` named parameters in that string
  167. using the named groups captured in the URL.
  168. If :attr:`url` is not set, ``get_redirect_url()`` tries to reverse the
  169. :attr:`pattern_name` using what was captured in the URL (both named and
  170. unnamed groups are used).
  171. If requested by :attr:`query_string`, it will also append the query
  172. string to the generated URL.
  173. Subclasses may implement any behavior they wish, as long as the method
  174. returns a redirect-ready URL string.