Base views

The following three classes provide much of the functionality needed to create Django views. You may think of them as parent views, which can be used by themselves or inherited from. They may not provide all the capabilities required for projects, in which case there are Mixins and Generic class-based views.

Many of Django’s built-in class-based views inherit from other class-based views or various mixins. Because this inheritance chain is very important, the ancestor 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 base view class. All other class-based views inherit from this base class. It isn’t strictly a generic view and thus can also be imported from django.views.

Method Flowchart

  1. setup()
  2. dispatch()
  3. http_method_not_allowed()
  4. options()

Example views.py:

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

Example urls.py:

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

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 as_view(**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_initkwargs attributes.

    When the view is called during the request/response cycle, the setup() method assigns the HttpRequest to the view’s request attribute, and any positional and/or keyword arguments captured from the URL pattern to the args and kwargs attributes, respectively. Then dispatch() is called.

    If a View subclass defines asynchronous (async def) method handlers, as_view() will mark the returned callable as a coroutine function. An ImproperlyConfigured exception will be raised if both asynchronous (async def) and synchronous (def) handlers are defined on a single view-class.

  • setup(request, *args, **kwargs)

    Performs key view initialization prior to dispatch().

    If overriding this method, you must call super().

  • dispatch(request, *args, **kwargs)

    The view part of the view – the method that accepts a request argument plus arguments, and returns an HTTP response.

    The default implementation will inspect the HTTP method and attempt to delegate to a method that matches the HTTP method; a GET will be delegated 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. See Supporting other HTTP methods for an example.

  • http_method_not_allowed(request, *args, **kwargs)

    If the view was called with an HTTP method it doesn’t support, this method is called instead.

    The default implementation returns HttpResponseNotAllowed with a list of allowed methods in plain text.

  • options(request, *args, **kwargs)

    Handles responding to requests for the OPTIONS HTTP verb. Returns a response with the Allow header containing a list of the view’s allowed HTTP method names.

    If the other HTTP methods handlers on the class are asynchronous (async def) then the response will be wrapped in a coroutine function for use with await.

TemplateView

class django.views.generic.base.TemplateView

Renders a given template, with the context containing parameters captured in the URL.

Ancestors (MRO)

This view inherits methods and attributes from the following views:

Method Flowchart

  1. setup()
  2. dispatch()
  3. http_method_not_allowed()
  4. get_context_data()

Example views.py:

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

Example urls.py:

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

Context

  • Populated (through ContextMixin) with the keyword arguments captured from the URL pattern that served the view.
  • You can also add context using the extra_context keyword argument 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 be interpolated against the parameters captured in the URL. Because keyword interpolation is always done (even if no arguments are passed in), any "%" characters in the URL must be written as "%%" so that Python will 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:

Method Flowchart

  1. setup()
  2. dispatch()
  3. http_method_not_allowed()
  4. get_redirect_url()

Example views.py:

  1. from django.shortcuts import get_object_or_404
  2. from django.views.generic.base import RedirectView
  3. from articles.models import Article
  4. class ArticleCounterRedirectView(RedirectView):
  5. permanent = False
  6. query_string = True
  7. pattern_name = "article-detail"
  8. def get_redirect_url(self, *args, **kwargs):
  9. article = get_object_or_404(Article, pk=kwargs["pk"])
  10. article.update_counter()
  11. 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. from article.views import ArticleCounterRedirectView, ArticleDetailView
  4. urlpatterns = [
  5. path(
  6. "counter/<int:pk>/",
  7. ArticleCounterRedirectView.as_view(),
  8. name="article-counter",
  9. ),
  10. path("details/<int:pk>/", ArticleDetailView.as_view(), name="article-detail"),
  11. path(
  12. "go-to-django/",
  13. RedirectView.as_view(url="https://www.djangoproject.com/"),
  14. name="go-to-django",
  15. ),
  16. ]

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 done using the same args and kwargs as are passed in for this view.

  • permanent

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

  • 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. If False, then the query string is discarded. By default, query_string is False.

Methods

  • get_redirect_url(*args, **kwargs)

    Constructs the target URL for redirection.

    The args and kwargs arguments are positional and/or keyword arguments captured from the URL pattern, respectively.

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

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

    If requested by query_string, it will also append the query string to the generated URL. Subclasses may implement any behavior they wish, as long as the method returns a redirect-ready URL string.