base.txt 8.5 KB

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