base.txt 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 inheritence 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 patterns, url
  30. from myapp.views import MyView
  31. urlpatterns = patterns('',
  32. url(r'^mine/$', MyView.as_view(), name='my-view'),
  33. )
  34. **Attributes**
  35. .. attribute:: http_method_names = ['get', 'post', 'put', 'delete', 'head', 'options', 'trace']
  36. The default list of HTTP method names that this view will accept.
  37. **Methods**
  38. .. classmethod:: as_view(**initkwargs)
  39. Returns a callable view that takes a request and returns a response::
  40. response = MyView.as_view(request)
  41. .. method:: dispatch(request, *args, **kwargs)
  42. The ``view`` part of the view -- the method that accepts a ``request``
  43. argument plus arguments, and returns a HTTP response.
  44. The default implementation will inspect the HTTP method and attempt to
  45. delegate to a method that matches the HTTP method; a ``GET`` will be
  46. delegated to :meth:`~View.get()`, a ``POST`` to :meth:`~View.post()`,
  47. and so on.
  48. The default implementation also sets ``request``, ``args`` and
  49. ``kwargs`` as instance variables, so any method on the view can know
  50. the full details of the request that was made to invoke the view.
  51. .. method:: http_method_not_allowed(request, *args, **kwargs)
  52. If the view was called with a HTTP method it doesn't support, this
  53. method is called instead.
  54. The default implementation returns ``HttpResponseNotAllowed`` with a
  55. list of allowed methods in plain text.
  56. .. method:: options(request, *args, **kwargs)
  57. Handles responding to requests for the OPTIONS HTTP verb. Returns a
  58. list of the allowed HTTP method names for the view.
  59. TemplateView
  60. ------------
  61. .. class:: django.views.generic.base.TemplateView
  62. Renders a given template, passing it a ``{{ params }}`` template variable,
  63. which is a dictionary of the parameters captured in the URL.
  64. **Ancestors (MRO)**
  65. This view inherits methods and attributes from the following views:
  66. * :class:`django.views.generic.base.TemplateView`
  67. * :class:`django.views.generic.base.TemplateResponseMixin`
  68. * :class:`django.views.generic.base.View`
  69. **Method Flowchart**
  70. 1. :meth:`dispatch()`
  71. 2. :meth:`http_method_not_allowed()`
  72. 3. :meth:`get_context_data()`
  73. **Example views.py**::
  74. from django.views.generic.base import TemplateView
  75. from articles.models import Article
  76. class HomePageView(TemplateView):
  77. template_name = "home.html"
  78. def get_context_data(self, **kwargs):
  79. context = super(HomePageView, self).get_context_data(**kwargs)
  80. context['latest_articles'] = Article.objects.all()[:5]
  81. return context
  82. **Example urls.py**::
  83. from django.conf.urls import patterns, url
  84. from myapp.views import HomePageView
  85. urlpatterns = patterns('',
  86. url(r'^$', HomePageView.as_view(), name='home'),
  87. )
  88. **Context**
  89. * ``params``: The dictionary of keyword arguments captured from the URL
  90. pattern that served the view.
  91. RedirectView
  92. ------------
  93. .. class:: django.views.generic.base.RedirectView
  94. Redirects to a given URL.
  95. The given URL may contain dictionary-style string formatting, which will be
  96. interpolated against the parameters captured in the URL. Because keyword
  97. interpolation is *always* done (even if no arguments are passed in), any
  98. ``"%"`` characters in the URL must be written as ``"%%"`` so that Python
  99. will convert them to a single percent sign on output.
  100. If the given URL is ``None``, Django will return an ``HttpResponseGone``
  101. (410).
  102. **Ancestors (MRO)**
  103. This view inherits methods and attributes from the following view:
  104. * :class:`django.views.generic.base.View`
  105. **Method Flowchart**
  106. 1. :meth:`dispatch()`
  107. 2. :meth:`http_method_not_allowed()`
  108. 3. :meth:`get_redirect_url()`
  109. **Example views.py**::
  110. from django.shortcuts import get_object_or_404
  111. from django.views.generic.base import RedirectView
  112. from articles.models import Article
  113. class ArticleCounterRedirectView(RedirectView):
  114. permanent = False
  115. query_string = True
  116. def get_redirect_url(self, pk):
  117. article = get_object_or_404(Article, pk=pk)
  118. article.update_counter()
  119. return reverse('product_detail', args=(pk,))
  120. **Example urls.py**::
  121. from django.conf.urls import patterns, url
  122. from django.views.generic.base import RedirectView
  123. from article.views import ArticleCounterRedirectView
  124. urlpatterns = patterns('',
  125. url(r'r^(?P<pk>\d+)/$', ArticleCounterRedirectView.as_view(), name='article-counter'),
  126. url(r'^go-to-django/$', RedirectView.as_view(url='http://djangoproject.com'), name='go-to-django'),
  127. )
  128. **Attributes**
  129. .. attribute:: url
  130. The URL to redirect to, as a string. Or ``None`` to raise a 410 (Gone)
  131. HTTP error.
  132. .. attribute:: permanent
  133. Whether the redirect should be permanent. The only difference here is
  134. the HTTP status code returned. If ``True``, then the redirect will use
  135. status code 301. If ``False``, then the redirect will use status code
  136. 302. By default, ``permanent`` is ``True``.
  137. .. attribute:: query_string
  138. Whether to pass along the GET query string to the new location. If
  139. ``True``, then the query string is appended to the URL. If ``False``,
  140. then the query string is discarded. By default, ``query_string`` is
  141. ``False``.
  142. **Methods**
  143. .. method:: get_redirect_url(**kwargs)
  144. Constructs the target URL for redirection.
  145. The default implementation uses :attr:`~RedirectView.url` as a starting
  146. string, performs expansion of ``%`` parameters in that string, as well
  147. as the appending of query string if requested by
  148. :attr:`~RedirectView.query_string`. Subclasses may implement any
  149. behavior they wish, as long as the method returns a redirect-ready URL
  150. string.