base.txt 8.3 KB

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