Open-Source Wikis

/

Django

/

Systems

/

Views

django/django

Views

django/views/ holds the view-side machinery. The directory is small — most of the framework's views are user-defined — but it ships the class-based view base classes, the generic CRUD views, the technical 500 page, and a handful of built-in views (i18n JavaScript catalog, static file serving, default error views).

Purpose

Provide the smallest set of view-layer abstractions: the View base class for class-based views, a generic CRUD hierarchy (ListView, DetailView, CreateView, UpdateView, DeleteView, date-based variants), and the standard error/debug pages.

Directory layout

django/views/
├── __init__.py
├── csrf.py             # the CSRF failure view (rendered when middleware rejects)
├── debug.py            # the technical 500 page; SafeExceptionReporterFilter
├── decorators/         # @csrf_exempt, @cache_page, @require_http_methods, …
├── defaults.py         # page_not_found, server_error, bad_request, permission_denied
├── i18n.py             # JavaScriptCatalog view (serves django.po as JS)
├── static.py           # serve(): for development static-file serving
├── generic/
│   ├── __init__.py
│   ├── base.py         # View, RedirectView, TemplateView, ContextMixin
│   ├── dates.py        # ArchiveIndexView, YearArchiveView, MonthArchiveView, DateDetailView
│   ├── detail.py       # DetailView, BaseDetailView, SingleObjectMixin
│   ├── edit.py         # FormView, CreateView, UpdateView, DeleteView, BaseFormView
│   └── list.py         # ListView, BaseListView, MultipleObjectMixin
└── templates/          # default error templates and CSRF failure template

Key abstractions

Type File Role
View views/generic/base.py The class-based view base; as_view() returns a callable
TemplateView views/generic/base.py Renders a template with context
RedirectView views/generic/base.py Performs a redirect
ListView / MultipleObjectMixin views/generic/list.py Paginated object listing
DetailView / SingleObjectMixin views/generic/detail.py Single-object detail page
FormView, CreateView, UpdateView, DeleteView views/generic/edit.py Form-driven CRUD
*ArchiveView, *DateDetailView views/generic/dates.py Date-organised archive views
technical_500_response, technical_404_response, default_urlconf views/debug.py Debug views
serve views/static.py Dev-only static file serving

How class-based views work

graph TD
    URLConf["urls.py:<br/>path('items/', ItemListView.as_view())"]
    AsView["View.as_view()<br/>returns a closure"]
    Resolver["URL resolver"]
    Closure["closure(request, *args, **kwargs)"]
    SetupHook["setUp / setup() hook"]
    Dispatch["dispatch(request)"]
    HttpMethod["get/post/put/...(request)"]

    URLConf --> AsView
    AsView --> Closure
    Resolver --> Closure
    Closure --> SetupHook
    SetupHook --> Dispatch
    Dispatch --> HttpMethod

View.as_view(**initkwargs) returns a closure that, when called by the resolver, instantiates the view, calls setup(request, *args, **kwargs) (which sets self.request, self.args, self.kwargs), and dispatches to a method named after the HTTP method (get, post, put, patch, delete, head, options, trace).

If the request method isn't supported, http_method_not_allowed() returns a 405. as_view() also handles HttpResponseNotAllowed for methods listed in http_method_names.

The view classes use a flat mixin hierarchy. BaseListView is the no-template version (returns a JSON-friendly response in subclasses); MultipleObjectTemplateResponseMixin adds the template rendering. ListView is the user-facing combination.

The technical 500 page

django/views/debug.py is one of the more interesting non-trivial modules: ~26 KB of code dedicated to rendering a debugger-friendly error page. It:

  • Captures the exception traceback and source context for each frame.
  • Snapshots local variables (truncating long strings and skipping huge objects).
  • Renders the request META, GET, POST, COOKIES, FILES.
  • Lists active settings, redacted by SafeExceptionReporterFilter (HIDDEN_SETTINGS matches things like *PASSWORD*, *SECRET*, *KEY*).
  • Includes the template error context if the exception came from a template.
  • Renders a CSS/HTML page that's deliberately styled to look like a 1990s error report.

technical_404_response is the much smaller cousin: when DEBUG = True and a Resolver404 propagates out, it shows the URL patterns that were tried.

Default error views

django/views/defaults.py exposes:

  • page_not_found(request, exception, template_name="404.html")
  • server_error(request, template_name="500.html")
  • bad_request(request, exception, template_name="400.html")
  • permission_denied(request, exception, template_name="403.html")

Override them by setting handler400, handler403, handler404, handler500 in your root URLconf.

View decorators

django/views/decorators/ holds short, single-file decorators:

  • cache.py@cache_page, @never_cache
  • csrf.py@csrf_exempt, @csrf_protect, @requires_csrf_token, @ensure_csrf_cookie
  • http.py@require_http_methods, @require_safe, @require_GET, @require_POST, @condition (ETag/Last-Modified)
  • gzip.py@gzip_page
  • vary.py@vary_on_headers, @vary_on_cookie
  • clickjacking.py@xframe_options_*
  • debug.py@sensitive_variables, @sensitive_post_parameters
  • common.py@no_append_slash
  • cache.py@cache_control

Integration points

  • URL routing (urls) — calls the view callable returned by as_view() or a function-based view directly.
  • Middleware (middleware) — wraps the view layer; process_view runs after URL resolution but before the view.
  • Templates (templates) — TemplateResponseMixin and the render shortcut produce template-backed responses.
  • Forms (forms) — FormView, CreateView, UpdateView integrate Form/ModelForm validation and rendering.
  • ORM (orm) — ListView, DetailView, the date-based views all consume querysets.
  • Auth (contrib/auth) — LoginRequiredMixin and PermissionRequiredMixin are mixins applied to class-based views.

Entry points for modification

  • Custom generic view: subclass one of the classes in views/generic/ and override the relevant hooks. The mixin pattern is opinionated — there's usually exactly one method to override per concern.
  • Customising the debug page: subclass SafeExceptionReporterFilter and set DEFAULT_EXCEPTION_REPORTER_FILTER. To completely replace the page, set DEFAULT_EXCEPTION_REPORTER to a custom subclass of ExceptionReporter.
  • New error view: write a function in your project and assign it to one of the handlerNNN URLconf hooks.
  • Decorator for a custom request property: add to views/decorators/ if it's reusable, otherwise keep it local.

Key source files

File Purpose
django/views/generic/base.py View, TemplateView, RedirectView, ContextMixin
django/views/generic/list.py ListView, BaseListView, MultipleObjectMixin
django/views/generic/detail.py DetailView, BaseDetailView, SingleObjectMixin
django/views/generic/edit.py FormView, CreateView, UpdateView, DeleteView
django/views/generic/dates.py Date-archive views
django/views/debug.py Technical 500 page, sensitive variable filtering
django/views/defaults.py Default 400/403/404/500 views
django/views/decorators/ Per-decorator modules
django/views/i18n.py JavaScriptCatalog view
django/views/static.py serve() for development
django/views/csrf.py The CSRF failure view

Where to read tests

  • tests/generic_views/ — class-based views.
  • tests/view_tests/ — function-based views, debug, decorators, defaults.
  • tests/decorators/ — view decorator tests.

Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.

Views – Django wiki | Factory