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