base.txt 8.2 KB

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