1. ==========
    
  2. Base views
    
  3. ==========
    
  4. 
    
  5. The following three classes provide much of the functionality needed to create
    
  6. Django views. You may think of them as *parent* views, which can be used by
    
  7. themselves or inherited from. They may not provide all the capabilities
    
  8. required for projects, in which case there are Mixins and Generic class-based
    
  9. views.
    
  10. 
    
  11. Many of Django's built-in class-based views inherit from other class-based
    
  12. views or various mixins. Because this inheritance chain is very important, the
    
  13. ancestor classes are  documented under the section title of **Ancestors (MRO)**.
    
  14. MRO is an acronym for Method Resolution Order.
    
  15. 
    
  16. ``View``
    
  17. ========
    
  18. 
    
  19. .. class:: django.views.generic.base.View
    
  20. 
    
  21.     The base view class. All other class-based views inherit from this base
    
  22.     class. It isn't strictly a generic view and thus can also be imported from
    
  23.     ``django.views``.
    
  24. 
    
  25.     **Method Flowchart**
    
  26. 
    
  27.     #. :meth:`setup()`
    
  28.     #. :meth:`dispatch()`
    
  29.     #. :meth:`http_method_not_allowed()`
    
  30.     #. :meth:`options()`
    
  31. 
    
  32.     **Example views.py**::
    
  33. 
    
  34.         from django.http import HttpResponse
    
  35.         from django.views import View
    
  36. 
    
  37.         class MyView(View):
    
  38. 
    
  39.             def get(self, request, *args, **kwargs):
    
  40.                 return HttpResponse('Hello, World!')
    
  41. 
    
  42.     **Example urls.py**::
    
  43. 
    
  44.         from django.urls import path
    
  45. 
    
  46.         from myapp.views import MyView
    
  47. 
    
  48.         urlpatterns = [
    
  49.             path('mine/', MyView.as_view(), name='my-view'),
    
  50.         ]
    
  51. 
    
  52.     **Attributes**
    
  53. 
    
  54.     .. attribute:: http_method_names
    
  55. 
    
  56.         The list of HTTP method names that this view will accept.
    
  57. 
    
  58.         Default::
    
  59. 
    
  60.             ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
    
  61. 
    
  62.     **Methods**
    
  63. 
    
  64.     .. classmethod:: as_view(**initkwargs)
    
  65. 
    
  66.         Returns a callable view that takes a request and returns a response::
    
  67. 
    
  68.             response = MyView.as_view()(request)
    
  69. 
    
  70.         The returned view has ``view_class`` and ``view_initkwargs``
    
  71.         attributes.
    
  72. 
    
  73.         When the view is called during the request/response cycle, the
    
  74.         :meth:`setup` method assigns the :class:`~django.http.HttpRequest` to
    
  75.         the view's ``request`` attribute, and any positional and/or keyword
    
  76.         arguments :ref:`captured from the URL pattern
    
  77.         <how-django-processes-a-request>` to the ``args`` and ``kwargs``
    
  78.         attributes, respectively. Then :meth:`dispatch` is called.
    
  79. 
    
  80.         If a ``View`` subclass defines asynchronous (``async def``) method
    
  81.         handlers, ``as_view()`` will mark the returned callable as a coroutine
    
  82.         function. An ``ImproperlyConfigured`` exception will be raised if both
    
  83.         asynchronous (``async def``) and synchronous (``def``) handlers are
    
  84.         defined on a single view-class.
    
  85. 
    
  86.         .. versionchanged:: 4.1
    
  87. 
    
  88.             Compatibility with asynchronous (``async def``) method handlers was
    
  89.             added.
    
  90. 
    
  91.     .. method:: setup(request, *args, **kwargs)
    
  92. 
    
  93.         Performs key view initialization prior to :meth:`dispatch`.
    
  94. 
    
  95.         If overriding this method, you must call ``super()``.
    
  96. 
    
  97.     .. method:: dispatch(request, *args, **kwargs)
    
  98. 
    
  99.         The ``view`` part of the view -- the method that accepts a ``request``
    
  100.         argument plus arguments, and returns an HTTP response.
    
  101. 
    
  102.         The default implementation will inspect the HTTP method and attempt to
    
  103.         delegate to a method that matches the HTTP method; a ``GET`` will be
    
  104.         delegated to ``get()``, a ``POST`` to ``post()``, and so on.
    
  105. 
    
  106.         By default, a ``HEAD`` request will be delegated to ``get()``.
    
  107.         If you need to handle ``HEAD`` requests in a different way than ``GET``,
    
  108.         you can override the ``head()`` method. See
    
  109.         :ref:`supporting-other-http-methods` for an example.
    
  110. 
    
  111.     .. method:: http_method_not_allowed(request, *args, **kwargs)
    
  112. 
    
  113.         If the view was called with an HTTP method it doesn't support, this
    
  114.         method is called instead.
    
  115. 
    
  116.         The default implementation returns ``HttpResponseNotAllowed`` with a
    
  117.         list of allowed methods in plain text.
    
  118. 
    
  119.     .. method:: options(request, *args, **kwargs)
    
  120. 
    
  121.         Handles responding to requests for the OPTIONS HTTP verb. Returns a
    
  122.         response with the ``Allow`` header containing a list of the view's
    
  123.         allowed HTTP method names.
    
  124. 
    
  125.         If the other HTTP methods handlers on the class are asynchronous
    
  126.         (``async def``) then the response will be wrapped in a coroutine
    
  127.         function for use with ``await``.
    
  128. 
    
  129.         .. versionchanged:: 4.1
    
  130. 
    
  131.             Compatibility with classes defining asynchronous (``async def``)
    
  132.             method handlers was added.
    
  133. 
    
  134. ``TemplateView``
    
  135. ================
    
  136. 
    
  137. .. class:: django.views.generic.base.TemplateView
    
  138. 
    
  139.     Renders a given template, with the context containing parameters captured
    
  140.     in the URL.
    
  141. 
    
  142.     **Ancestors (MRO)**
    
  143. 
    
  144.     This view inherits methods and attributes from the following views:
    
  145. 
    
  146.     * :class:`django.views.generic.base.TemplateResponseMixin`
    
  147.     * :class:`django.views.generic.base.ContextMixin`
    
  148.     * :class:`django.views.generic.base.View`
    
  149. 
    
  150.     **Method Flowchart**
    
  151. 
    
  152.     #. :meth:`~django.views.generic.base.View.setup()`
    
  153.     #. :meth:`~django.views.generic.base.View.dispatch()`
    
  154.     #. :meth:`~django.views.generic.base.View.http_method_not_allowed()`
    
  155.     #. :meth:`~django.views.generic.base.ContextMixin.get_context_data()`
    
  156. 
    
  157.     **Example views.py**::
    
  158. 
    
  159.         from django.views.generic.base import TemplateView
    
  160. 
    
  161.         from articles.models import Article
    
  162. 
    
  163.         class HomePageView(TemplateView):
    
  164. 
    
  165.             template_name = "home.html"
    
  166. 
    
  167.             def get_context_data(self, **kwargs):
    
  168.                 context = super().get_context_data(**kwargs)
    
  169.                 context['latest_articles'] = Article.objects.all()[:5]
    
  170.                 return context
    
  171. 
    
  172.     **Example urls.py**::
    
  173. 
    
  174.         from django.urls import path
    
  175. 
    
  176.         from myapp.views import HomePageView
    
  177. 
    
  178.         urlpatterns = [
    
  179.             path('', HomePageView.as_view(), name='home'),
    
  180.         ]
    
  181. 
    
  182.     **Context**
    
  183. 
    
  184.     * Populated (through :class:`~django.views.generic.base.ContextMixin`) with
    
  185.       the keyword arguments captured from the URL pattern that served the view.
    
  186.     * You can also add context using the
    
  187.       :attr:`~django.views.generic.base.ContextMixin.extra_context` keyword
    
  188.       argument for :meth:`~django.views.generic.base.View.as_view`.
    
  189. 
    
  190. ``RedirectView``
    
  191. ================
    
  192. 
    
  193. .. class:: django.views.generic.base.RedirectView
    
  194. 
    
  195.     Redirects to a given URL.
    
  196. 
    
  197.     The given URL may contain dictionary-style string formatting, which will be
    
  198.     interpolated against the parameters captured in the URL. Because keyword
    
  199.     interpolation is *always* done (even if no arguments are passed in), any
    
  200.     ``"%"`` characters in the URL must be written as ``"%%"`` so that Python
    
  201.     will convert them to a single percent sign on output.
    
  202. 
    
  203.     If the given URL is ``None``, Django will return an ``HttpResponseGone``
    
  204.     (410).
    
  205. 
    
  206.     **Ancestors (MRO)**
    
  207. 
    
  208.     This view inherits methods and attributes from the following view:
    
  209. 
    
  210.     * :class:`django.views.generic.base.View`
    
  211. 
    
  212.     **Method Flowchart**
    
  213. 
    
  214.     #. :meth:`~django.views.generic.base.View.setup()`
    
  215.     #. :meth:`~django.views.generic.base.View.dispatch()`
    
  216.     #. :meth:`~django.views.generic.base.View.http_method_not_allowed()`
    
  217.     #. :meth:`get_redirect_url()`
    
  218. 
    
  219.     **Example views.py**::
    
  220. 
    
  221.         from django.shortcuts import get_object_or_404
    
  222.         from django.views.generic.base import RedirectView
    
  223. 
    
  224.         from articles.models import Article
    
  225. 
    
  226.         class ArticleCounterRedirectView(RedirectView):
    
  227. 
    
  228.             permanent = False
    
  229.             query_string = True
    
  230.             pattern_name = 'article-detail'
    
  231. 
    
  232.             def get_redirect_url(self, *args, **kwargs):
    
  233.                 article = get_object_or_404(Article, pk=kwargs['pk'])
    
  234.                 article.update_counter()
    
  235.                 return super().get_redirect_url(*args, **kwargs)
    
  236. 
    
  237.     **Example urls.py**::
    
  238. 
    
  239.         from django.urls import path
    
  240.         from django.views.generic.base import RedirectView
    
  241. 
    
  242.         from article.views import ArticleCounterRedirectView, ArticleDetailView
    
  243. 
    
  244.         urlpatterns = [
    
  245.             path('counter/<int:pk>/', ArticleCounterRedirectView.as_view(), name='article-counter'),
    
  246.             path('details/<int:pk>/', ArticleDetailView.as_view(), name='article-detail'),
    
  247.             path('go-to-django/', RedirectView.as_view(url='https://www.djangoproject.com/'), name='go-to-django'),
    
  248.         ]
    
  249. 
    
  250.     **Attributes**
    
  251. 
    
  252.     .. attribute:: url
    
  253. 
    
  254.         The URL to redirect to, as a string. Or ``None`` to raise a 410 (Gone)
    
  255.         HTTP error.
    
  256. 
    
  257.     .. attribute:: pattern_name
    
  258. 
    
  259.         The name of the URL pattern to redirect to. Reversing will be done
    
  260.         using the same args and kwargs as are passed in for this view.
    
  261. 
    
  262.     .. attribute:: permanent
    
  263. 
    
  264.         Whether the redirect should be permanent. The only difference here is
    
  265.         the HTTP status code returned. If ``True``, then the redirect will use
    
  266.         status code 301. If ``False``, then the redirect will use status code
    
  267.         302. By default, ``permanent`` is ``False``.
    
  268. 
    
  269.     .. attribute:: query_string
    
  270. 
    
  271.         Whether to pass along the GET query string to the new location. If
    
  272.         ``True``, then the query string is appended to the URL. If ``False``,
    
  273.         then the query string is discarded. By default, ``query_string`` is
    
  274.         ``False``.
    
  275. 
    
  276.     **Methods**
    
  277. 
    
  278.     .. method:: get_redirect_url(*args, **kwargs)
    
  279. 
    
  280.         Constructs the target URL for redirection.
    
  281. 
    
  282.         The ``args`` and ``kwargs`` arguments are positional and/or keyword
    
  283.         arguments :ref:`captured from the URL pattern
    
  284.         <how-django-processes-a-request>`, respectively.
    
  285. 
    
  286.         The default implementation uses :attr:`url` as a starting
    
  287.         string and performs expansion of ``%`` named parameters in that string
    
  288.         using the named groups captured in the URL.
    
  289. 
    
  290.         If :attr:`url` is not set, ``get_redirect_url()`` tries to reverse the
    
  291.         :attr:`pattern_name` using what was captured in the URL (both named and
    
  292.         unnamed groups are used).
    
  293. 
    
  294.         If requested by :attr:`query_string`, it will also append the query
    
  295.         string to the generated URL.
    
  296.         Subclasses may implement any behavior they wish, as long as the method
    
  297.         returns a redirect-ready URL string.