| 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 |
|
| 38 |
class MyView(View): |
| 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 |
.. method:: setup(request, *args, **kwargs) |
| 87 |
|
| 88 |
Performs key view initialization prior to :meth:`dispatch`. |
| 89 |
|
| 90 |
Assigns the :class:`~django.http.HttpRequest` to the view's ``request`` |
| 91 |
attribute, and any positional and/or keyword arguments |
| 92 |
:ref:`captured from the URL pattern <how-django-processes-a-request>` |
| 93 |
to the ``args`` and ``kwargs`` attributes, respectively. |
| 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 |
``TemplateView`` |
| 130 |
================ |
| 131 |
|
| 132 |
.. class:: django.views.generic.base.TemplateView |
| 133 |
|
| 134 |
Renders a given template, with the context containing parameters captured |
| 135 |
in the URL. |
| 136 |
|
| 137 |
**Ancestors (MRO)** |
| 138 |
|
| 139 |
This view inherits methods and attributes from the following views: |
| 140 |
|
| 141 |
* :class:`django.views.generic.base.TemplateResponseMixin` |
| 142 |
* :class:`django.views.generic.base.ContextMixin` |
| 143 |
* :class:`django.views.generic.base.View` |
| 144 |
|
| 145 |
**Method Flowchart** |
| 146 |
|
| 147 |
#. :meth:`~django.views.generic.base.View.setup()` |
| 148 |
#. :meth:`~django.views.generic.base.View.dispatch()` |
| 149 |
#. :meth:`~django.views.generic.base.View.http_method_not_allowed()` |
| 150 |
#. :meth:`~django.views.generic.base.ContextMixin.get_context_data()` |
| 151 |
|
| 152 |
**Example views.py**:: |
| 153 |
|
| 154 |
from django.views.generic.base import TemplateView |
| 155 |
|
| 156 |
from articles.models import Article |
| 157 |
|
| 158 |
|
| 159 |
class HomePageView(TemplateView): |
| 160 |
template_name = "home.html" |
| 161 |
|
| 162 |
def get_context_data(self, **kwargs): |
| 163 |
context = super().get_context_data(**kwargs) |
| 164 |
context["latest_articles"] = Article.objects.all()[:5] |
| 165 |
return context |
| 166 |
|
| 167 |
**Example urls.py**:: |
| 168 |
|
| 169 |
from django.urls import path |
| 170 |
|
| 171 |
from myapp.views import HomePageView |
| 172 |
|
| 173 |
urlpatterns = [ |
| 174 |
path("", HomePageView.as_view(), name="home"), |
| 175 |
] |
| 176 |
|
| 177 |
**Context** |
| 178 |
|
| 179 |
* Populated (through :class:`~django.views.generic.base.ContextMixin`) with |
| 180 |
the keyword arguments captured from the URL pattern that served the view. |
| 181 |
* You can also add context using the |
| 182 |
:attr:`~django.views.generic.base.ContextMixin.extra_context` keyword |
| 183 |
argument for :meth:`~django.views.generic.base.View.as_view`. |
| 184 |
|
| 185 |
``RedirectView`` |
| 186 |
================ |
| 187 |
|
| 188 |
.. class:: django.views.generic.base.RedirectView |
| 189 |
|
| 190 |
Redirects to a given URL. |
| 191 |
|
| 192 |
The given URL may contain dictionary-style string formatting, which will be |
| 193 |
interpolated against the parameters captured in the URL. Because keyword |
| 194 |
interpolation is *always* done (even if no arguments are passed in), any |
| 195 |
``"%"`` characters in the URL must be written as ``"%%"`` so that Python |
| 196 |
will convert them to a single percent sign on output. |
| 197 |
|
| 198 |
If the given URL is ``None``, Django will return an ``HttpResponseGone`` |
| 199 |
(410). |
| 200 |
|
| 201 |
**Ancestors (MRO)** |
| 202 |
|
| 203 |
This view inherits methods and attributes from the following view: |
| 204 |
|
| 205 |
* :class:`django.views.generic.base.View` |
| 206 |
|
| 207 |
**Method Flowchart** |
| 208 |
|
| 209 |
#. :meth:`~django.views.generic.base.View.setup()` |
| 210 |
#. :meth:`~django.views.generic.base.View.dispatch()` |
| 211 |
#. :meth:`~django.views.generic.base.View.http_method_not_allowed()` |
| 212 |
#. :meth:`get_redirect_url()` |
| 213 |
|
| 214 |
**Example views.py**:: |
| 215 |
|
| 216 |
from django.shortcuts import get_object_or_404 |
| 217 |
from django.views.generic.base import RedirectView |
| 218 |
|
| 219 |
from articles.models import Article |
| 220 |
|
| 221 |
|
| 222 |
class ArticleCounterRedirectView(RedirectView): |
| 223 |
permanent = False |
| 224 |
query_string = True |
| 225 |
pattern_name = "article-detail" |
| 226 |
|
| 227 |
def get_redirect_url(self, *args, **kwargs): |
| 228 |
article = get_object_or_404(Article, pk=kwargs["pk"]) |
| 229 |
article.update_counter() |
| 230 |
return super().get_redirect_url(*args, **kwargs) |
| 231 |
|
| 232 |
**Example urls.py**:: |
| 233 |
|
| 234 |
from django.urls import path |
| 235 |
from django.views.generic.base import RedirectView |
| 236 |
|
| 237 |
from article.views import ArticleCounterRedirectView, ArticleDetailView |
| 238 |
|
| 239 |
urlpatterns = [ |
| 240 |
path( |
| 241 |
"counter/<int:pk>/", |
| 242 |
ArticleCounterRedirectView.as_view(), |
| 243 |
name="article-counter", |
| 244 |
), |
| 245 |
path("details/<int:pk>/", ArticleDetailView.as_view(), name="article-detail"), |
| 246 |
path( |
| 247 |
"go-to-django/", |
| 248 |
RedirectView.as_view(url="https://www.djangoproject.com/"), |
| 249 |
name="go-to-django", |
| 250 |
), |
| 251 |
] |
| 252 |
|
| 253 |
**Attributes** |
| 254 |
|
| 255 |
.. attribute:: url |
| 256 |
|
| 257 |
The URL to redirect to, as a string. Or ``None`` to raise a 410 (Gone) |
| 258 |
HTTP error. |
| 259 |
|
| 260 |
.. attribute:: pattern_name |
| 261 |
|
| 262 |
The name of the URL pattern to redirect to. Reversing will be done |
| 263 |
using the same args and kwargs as are passed in for this view. |
| 264 |
|
| 265 |
.. attribute:: permanent |
| 266 |
|
| 267 |
Whether the redirect should be permanent. The only difference here is |
| 268 |
the HTTP status code returned. If ``True``, then the redirect will use |
| 269 |
status code 301. If ``False``, then the redirect will use status code |
| 270 |
302. By default, ``permanent`` is ``False``. |
| 271 |
|
| 272 |
.. attribute:: query_string |
| 273 |
|
| 274 |
Whether to pass along the GET query string to the new location. If |
| 275 |
``True``, then the query string is appended to the URL. If ``False``, |
| 276 |
then the query string is discarded. By default, ``query_string`` is |
| 277 |
``False``. |
| 278 |
|
| 279 |
**Methods** |
| 280 |
|
| 281 |
.. method:: get_redirect_url(*args, **kwargs) |
| 282 |
|
| 283 |
Constructs the target URL for redirection. |
| 284 |
|
| 285 |
The ``args`` and ``kwargs`` arguments are positional and/or keyword |
| 286 |
arguments :ref:`captured from the URL pattern |
| 287 |
<how-django-processes-a-request>`, respectively. |
| 288 |
|
| 289 |
The default implementation uses :attr:`url` as a starting |
| 290 |
string and performs expansion of ``%`` named parameters in that string |
| 291 |
using the named groups captured in the URL. |
| 292 |
|
| 293 |
If :attr:`url` is not set, ``get_redirect_url()`` tries to reverse the |
| 294 |
:attr:`pattern_name` using what was captured in the URL (both named and |
| 295 |
unnamed groups are used). |
| 296 |
|
| 297 |
If requested by :attr:`query_string`, it will also append the query |
| 298 |
string to the generated URL. |
| 299 |
Subclasses may implement any behavior they wish, as long as the method |
| 300 |
returns a redirect-ready URL string. |