base.txt 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. ``RedirectView``
  104. ================
  105. .. class:: django.views.generic.base.RedirectView
  106. Redirects to a given URL.
  107. The given URL may contain dictionary-style string formatting, which will be
  108. interpolated against the parameters captured in the URL. Because keyword
  109. interpolation is *always* done (even if no arguments are passed in), any
  110. ``"%"`` characters in the URL must be written as ``"%%"`` so that Python
  111. will convert them to a single percent sign on output.
  112. If the given URL is ``None``, Django will return an ``HttpResponseGone``
  113. (410).
  114. **Ancestors (MRO)**
  115. This view inherits methods and attributes from the following view:
  116. * :class:`django.views.generic.base.View`
  117. **Method Flowchart**
  118. 1. :meth:`~django.views.generic.base.View.dispatch()`
  119. 2. :meth:`~django.views.generic.base.View.http_method_not_allowed()`
  120. 3. :meth:`get_redirect_url()`
  121. **Example views.py**::
  122. from django.shortcuts import get_object_or_404
  123. from django.views.generic.base import RedirectView
  124. from articles.models import Article
  125. class ArticleCounterRedirectView(RedirectView):
  126. permanent = False
  127. query_string = True
  128. pattern_name = 'article-detail'
  129. def get_redirect_url(self, *args, **kwargs):
  130. article = get_object_or_404(Article, pk=kwargs['pk'])
  131. article.update_counter()
  132. return super().get_redirect_url(*args, **kwargs)
  133. **Example urls.py**::
  134. from django.conf.urls import url
  135. from django.views.generic.base import RedirectView
  136. from article.views import ArticleCounterRedirectView, ArticleDetail
  137. urlpatterns = [
  138. url(r'^counter/(?P<pk>[0-9]+)/$', ArticleCounterRedirectView.as_view(), name='article-counter'),
  139. url(r'^details/(?P<pk>[0-9]+)/$', ArticleDetail.as_view(), name='article-detail'),
  140. url(r'^go-to-django/$', RedirectView.as_view(url='https://djangoproject.com'), name='go-to-django'),
  141. ]
  142. **Attributes**
  143. .. attribute:: url
  144. The URL to redirect to, as a string. Or ``None`` to raise a 410 (Gone)
  145. HTTP error.
  146. .. attribute:: pattern_name
  147. The name of the URL pattern to redirect to. Reversing will be done
  148. using the same args and kwargs as are passed in for this view.
  149. .. attribute:: permanent
  150. Whether the redirect should be permanent. The only difference here is
  151. the HTTP status code returned. If ``True``, then the redirect will use
  152. status code 301. If ``False``, then the redirect will use status code
  153. 302. By default, ``permanent`` is ``False``.
  154. .. attribute:: query_string
  155. Whether to pass along the GET query string to the new location. If
  156. ``True``, then the query string is appended to the URL. If ``False``,
  157. then the query string is discarded. By default, ``query_string`` is
  158. ``False``.
  159. **Methods**
  160. .. method:: get_redirect_url(*args, **kwargs)
  161. Constructs the target URL for redirection.
  162. The default implementation uses :attr:`url` as a starting
  163. string and performs expansion of ``%`` named parameters in that string
  164. using the named groups captured in the URL.
  165. If :attr:`url` is not set, ``get_redirect_url()`` tries to reverse the
  166. :attr:`pattern_name` using what was captured in the URL (both named and
  167. unnamed groups are used).
  168. If requested by :attr:`query_string`, it will also append the query
  169. string to the generated URL.
  170. Subclasses may implement any behavior they wish, as long as the method
  171. returns a redirect-ready URL string.