Base views
Many of Django's built-in class-based views inherit from other class-basedviews or various mixins. Because this inheritance chain is very important, theancestor classes are documented under the section title of Ancestors (MRO).MRO is an acronym for Method Resolution Order.
- class
View
- The master class-based base view. All other class-based views inherit fromthis base class. It isn't strictly a generic view and thus can also beimported from
django.views
.
Method Flowchart
dispatch()
options()
Example views.py:
Example urls.py:
- from django.urls import path
- from myapp.views import MyView
- urlpatterns = [
- path('mine/', MyView.as_view(), name='my-view'),
- ]
Attributes
http_method_names
- The list of HTTP method names that this view will accept.
Default:
Methods
- classmethod
asview
(**initkwargs_) - Returns a callable view that takes a request and returns a response:
- response = MyView.as_view()(request)
The returned view has view_class
and view_initkwargs
attributes.
When the view is called during the request/response cycle, the method assigns the HttpRequest
tothe view's request
attribute, and any positional and/or keywordarguments to the args
and kwargs
attributes, respectively. Then dispatch()
is called.
setup
(request, *args, **kwargs)- New in Django 2.2:
Initializes view instance attributes: self.request
, self.args
,and self.kwargs
prior to dispatch()
.
Overriding this method allows mixins to setup instance attributes forreuse in child classes. When overriding this method, you must callsuper()
.
dispatch
(request, *args, **kwargs)
The default implementation will inspect the HTTP method and attempt todelegate to a method that matches the HTTP method; a GET
will bedelegated to , a POST
to post()
, and so on.
httpmethod_not_allowed
(_request, *args, **kwargs)- If the view was called with a HTTP method it doesn't support, thismethod is called instead.
The default implementation returns HttpResponseNotAllowed
with alist of allowed methods in plain text.
options
(request, *args, **kwargs)- Handles responding to requests for the OPTIONS HTTP verb. Returns aresponse with the
Allow
header containing a list of the view'sallowed HTTP method names.
- class
django.views.generic.base.
TemplateView
- Renders a given template, with the context containing parameters capturedin the URL.
Ancestors (MRO)
This view inherits methods and attributes from the following views:
django.views.generic.base.ContextMixin
Method Flowcharthttp_method_not_allowed()
Example views.py:
Example urls.py:
- from django.urls import path
- from myapp.views import HomePageView
- urlpatterns = [
- path('', HomePageView.as_view(), name='home'),
- ]
Context
- Populated (through
ContextMixin
) withthe keyword arguments captured from the URL pattern that served the view. - You can also add context using the keywordargument for
as_view()
.
- class
django.views.generic.base.
RedirectView
- Redirects to a given URL.
The given URL may contain dictionary-style string formatting, which will beinterpolated against the parameters captured in the URL. Because keywordinterpolation is always done (even if no arguments are passed in), any"%"
characters in the URL must be written as so that Pythonwill convert them to a single percent sign on output.
If the given URL is None
, Django will return an HttpResponseGone
(410).
Ancestors (MRO)
This view inherits methods and attributes from the following view:
http_method_not_allowed()
Example views.py:
Example urls.py:
- from django.urls import path
- from django.views.generic.base import RedirectView
- from article.views import ArticleCounterRedirectView, ArticleDetail
- urlpatterns = [
- path('counter/<int:pk>/', ArticleCounterRedirectView.as_view(), name='article-counter'),
- path('details/<int:pk>/', ArticleDetail.as_view(), name='article-detail'),
- path('go-to-django/', RedirectView.as_view(url='https://djangoproject.com'), name='go-to-django'),
- ]
Attributes
url
The URL to redirect to, as a string. Or
None
to raise a 410 (Gone)HTTP error.pattern_name
The name of the URL pattern to redirect to. Reversing will be doneusing the same args and kwargs as are passed in for this view.
Whether the redirect should be permanent. The only difference here isthe HTTP status code returned. If
True
, then the redirect will usestatus code 301. IfFalse
, then the redirect will use status code302. By default,permanent
isFalse
.query_string
- Whether to pass along the GET query string to the new location. If
True
, then the query string is appended to the URL. IfFalse
,then the query string is discarded. By default,query_string
isFalse
.
Methods
The default implementation uses as a startingstring and performs expansion of %
named parameters in that stringusing the named groups captured in the URL.
If requested by , it will also append the querystring to the generated URL.Subclasses may implement any behavior they wish, as long as the methodreturns a redirect-ready URL string.