Base views

The following three classes provide much of the functionality needed to createDjango views. You may think of them as parent views, which can be used bythemselves or inherited from. They may not provide all the capabilitiesrequired for projects, in which case there are Mixins and Generic class-basedviews.

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.

View

  • class django.views.generic.base.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

  1. from django.http import HttpResponse
  2. from django.views import View
  3.  
  4. class MyView(View):
  5.  
  6. def get(self, request, *args, **kwargs):
  7. return HttpResponse('Hello, World!')

Example urls.py:

  1. from django.urls import path
  2.  
  3. from myapp.views import MyView
  4.  
  5. urlpatterns = [
  6. path('mine/', MyView.as_view(), name='my-view'),
  7. ]

Attributes

  • http_method_names
  • The list of HTTP method names that this view will accept.

Default:

  1. ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

Methods

  • classmethod asview(**initkwargs_)
  • Returns a callable view that takes a request and returns a response:
  1. response = MyView.as_view()(request)

The returned view has view_class and view_initkwargsattributes.

When the view is called during the request/response cycle, thesetup() method assigns the HttpRequest tothe view's request attribute, and any positional and/or keywordarguments captured from the URL pattern to the args and kwargsattributes, 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 view part of the view — the method that accepts a requestargument plus arguments, and returns a HTTP response.

The default implementation will inspect the HTTP method and attempt todelegate to a method that matches the HTTP method; a GET will bedelegated to get(), a POST to post(), and so on.

By default, a HEAD request will be delegated to get().If you need to handle HEAD requests in a different way than GET,you can override the head() method. SeeSupporting other HTTP methods for an example.

  • 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.

TemplateView

  • 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:

  1. from django.views.generic.base import TemplateView
  2.  
  3. from articles.models import Article
  4.  
  5. class HomePageView(TemplateView):
  6.  
  7. template_name = "home.html"
  8.  
  9. def get_context_data(self, **kwargs):
  10. context = super().get_context_data(**kwargs)
  11. context['latest_articles'] = Article.objects.all()[:5]
  12. return context

Example urls.py:

  1. from django.urls import path
  2.  
  3. from myapp.views import HomePageView
  4.  
  5. urlpatterns = [
  6. path('', HomePageView.as_view(), name='home'),
  7. ]

Context

  • Populated (through ContextMixin) withthe keyword arguments captured from the URL pattern that served the view.
  • You can also add context using theextra_context keywordargument for as_view().

RedirectView

  • 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:

  1. from django.shortcuts import get_object_or_404
  2. from django.views.generic.base import RedirectView
  3.  
  4. from articles.models import Article
  5.  
  6. class ArticleCounterRedirectView(RedirectView):
  7.  
  8. permanent = False
  9. query_string = True
  10. pattern_name = 'article-detail'
  11.  
  12. def get_redirect_url(self, *args, **kwargs):
  13. article = get_object_or_404(Article, pk=kwargs['pk'])
  14. article.update_counter()
  15. return super().get_redirect_url(*args, **kwargs)

Example urls.py:

  1. from django.urls import path
  2. from django.views.generic.base import RedirectView
  3.  
  4. from article.views import ArticleCounterRedirectView, ArticleDetail
  5.  
  6. urlpatterns = [
  7. path('counter/<int:pk>/', ArticleCounterRedirectView.as_view(), name='article-counter'),
  8. path('details/<int:pk>/', ArticleDetail.as_view(), name='article-detail'),
  9. path('go-to-django/', RedirectView.as_view(url='https://djangoproject.com'), name='go-to-django'),
  10. ]

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.

  • permanent

  • Whether the redirect should be permanent. The only difference here isthe HTTP status code returned. If True, then the redirect will usestatus code 301. If False, then the redirect will use status code302. By default, permanent is False.

  • query_string

  • Whether to pass along the GET query string to the new location. IfTrue, then the query string is appended to the URL. If False,then the query string is discarded. By default, query_string isFalse.

Methods

  • getredirect_url(args, *kwargs_)
  • Constructs the target URL for redirection.

The default implementation uses url as a startingstring and performs expansion of % named parameters in that stringusing the named groups captured in the URL.

If url is not set, get_redirect_url() tries to reverse thepattern_name using what was captured in the URL (both named andunnamed groups are used).

If requested by query_string, 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.