{"title":"基于类的视图","version":"2.1","locale":"zh-hans","docname":"topics/class-based-views/index","url":"/zh-hans/2.1/topics/class-based-views/","canonical":"https://djangodocs.dev/zh-hans/2.1/topics/class-based-views/","summary":"视图是可调用的，能接受用户的请求并返回响应。视图远不只是个函数，Django提供了一些可用作视图的类的示例，允许你通过继承和复用构建自己的视图并且复用这些代码。虽然接下来还会介绍一些用于简单任务的通用视图，但你可能想自己设计可复用的视图结构，以便针对某些特殊场景。详情请见 class-based views reference…","html":"<h1>基于类的视图<a class=\"heading-anchor\" href=\"#class-based-views\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>视图是可调用的，能接受用户的请求并返回响应。视图远不只是个函数，Django提供了一些可用作视图的类的示例，允许你通过继承和复用构建自己的视图并且复用这些代码。虽然接下来还会介绍一些用于简单任务的通用视图，但你可能想自己设计可复用的视图结构，以便针对某些特殊场景。详情请见 class-based views reference documentation&lt;/ref/class-based-views/index&gt; 。</p>\n<div class=\"toctree-wrapper compound\">\n<ul>\n<li class=\"toctree-l1\"><a class=\"reference internal\" href=\"/zh-hans/2.1/topics/class-based-views/intro/\">基于类的视图</a></li>\n<li class=\"toctree-l1\"><a class=\"reference internal\" href=\"/zh-hans/2.1/topics/class-based-views/generic-display/\">Built-in class-based generic views</a></li>\n<li class=\"toctree-l1\"><a class=\"reference internal\" href=\"/zh-hans/2.1/topics/class-based-views/generic-editing/\">Form handling with class-based views</a></li>\n<li class=\"toctree-l1\"><a class=\"reference internal\" href=\"/zh-hans/2.1/topics/class-based-views/mixins/\">Using mixins with class-based views</a></li>\n</ul>\n</div>\n<section id=\"basic-examples\">\n<h2>Basic examples<a class=\"heading-anchor\" href=\"#basic-examples\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Django provides base view classes which will suit a wide range of applications.\nAll views inherit from the <a class=\"reference internal\" href=\"/zh-hans/2.1/ref/class-based-views/base/#django.views.generic.base.View\" title=\"django.views.generic.base.View\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">View</span></code></a> class, which\nhandles linking the view in to the URLs, HTTP method dispatching and other\nsimple features. <a class=\"reference internal\" href=\"/zh-hans/2.1/ref/class-based-views/base/#django.views.generic.base.RedirectView\" title=\"django.views.generic.base.RedirectView\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RedirectView</span></code></a> is for a\nsimple HTTP redirect, and <a class=\"reference internal\" href=\"/zh-hans/2.1/ref/class-based-views/base/#django.views.generic.base.TemplateView\" title=\"django.views.generic.base.TemplateView\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">TemplateView</span></code></a>\nextends the base class to make it also render a template.</p>\n</section>\n<section id=\"simple-usage-in-your-urlconf\">\n<h2>Simple usage in your URLconf<a class=\"heading-anchor\" href=\"#simple-usage-in-your-urlconf\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>The simplest way to use generic views is to create them directly in your\nURLconf. If you're only changing a few simple attributes on a class-based view,\nyou can simply pass them into the\n<a class=\"reference internal\" href=\"/zh-hans/2.1/ref/class-based-views/base/#django.views.generic.base.View.as_view\" title=\"django.views.generic.base.View.as_view\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">as_view()</span></code></a> method call itself:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.urls</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">path</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.views.generic</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">TemplateView</span>\n\n<span class=\"n\">urlpatterns</span> <span class=\"o\">=</span> <span class=\"p\">[</span>\n    <span class=\"n\">path</span><span class=\"p\">(</span><span class=\"s1\">&#39;about/&#39;</span><span class=\"p\">,</span> <span class=\"n\">TemplateView</span><span class=\"o\">.</span><span class=\"n\">as_view</span><span class=\"p\">(</span><span class=\"n\">template_name</span><span class=\"o\">=</span><span class=\"s2\">&quot;about.html&quot;</span><span class=\"p\">)),</span>\n<span class=\"p\">]</span>\n</code></pre></div>\n<p>Any arguments passed to <a class=\"reference internal\" href=\"/zh-hans/2.1/ref/class-based-views/base/#django.views.generic.base.View.as_view\" title=\"django.views.generic.base.View.as_view\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">as_view()</span></code></a> will\noverride attributes set on the class. In this example, we set <code class=\"docutils literal notranslate\"><span class=\"pre\">template_name</span></code>\non the <code class=\"docutils literal notranslate\"><span class=\"pre\">TemplateView</span></code>. A similar overriding pattern can be used for the\n<code class=\"docutils literal notranslate\"><span class=\"pre\">url</span></code> attribute on <a class=\"reference internal\" href=\"/zh-hans/2.1/ref/class-based-views/base/#django.views.generic.base.RedirectView\" title=\"django.views.generic.base.RedirectView\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RedirectView</span></code></a>.</p>\n</section>\n<section id=\"subclassing-generic-views\">\n<h2>Subclassing generic views<a class=\"heading-anchor\" href=\"#subclassing-generic-views\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>The second, more powerful way to use generic views is to inherit from an\nexisting view and override attributes (such as the <code class=\"docutils literal notranslate\"><span class=\"pre\">template_name</span></code>) or\nmethods (such as <code class=\"docutils literal notranslate\"><span class=\"pre\">get_context_data</span></code>) in your subclass to provide new values\nor methods. Consider, for example, a view that just displays one template,\n<code class=\"docutils literal notranslate\"><span class=\"pre\">about.html</span></code>. Django has a generic view to do this -\n<a class=\"reference internal\" href=\"/zh-hans/2.1/ref/class-based-views/base/#django.views.generic.base.TemplateView\" title=\"django.views.generic.base.TemplateView\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">TemplateView</span></code></a> - so we can just subclass it,\nand override the template name:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"c1\"># some_app/views.py</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.views.generic</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">TemplateView</span>\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">AboutView</span><span class=\"p\">(</span><span class=\"n\">TemplateView</span><span class=\"p\">):</span>\n    <span class=\"n\">template_name</span> <span class=\"o\">=</span> <span class=\"s2\">&quot;about.html&quot;</span>\n</code></pre></div>\n<p>Then we just need to add this new view into our URLconf.\n<a class=\"reference internal\" href=\"/zh-hans/2.1/ref/class-based-views/base/#django.views.generic.base.TemplateView\" title=\"django.views.generic.base.TemplateView\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">TemplateView</span></code></a> is a class, not a function,\nso we point the URL to the <a class=\"reference internal\" href=\"/zh-hans/2.1/ref/class-based-views/base/#django.views.generic.base.View.as_view\" title=\"django.views.generic.base.View.as_view\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">as_view()</span></code></a>\nclass method instead, which provides a function-like entry to class-based\nviews:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"c1\"># urls.py</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.urls</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">path</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">some_app.views</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">AboutView</span>\n\n<span class=\"n\">urlpatterns</span> <span class=\"o\">=</span> <span class=\"p\">[</span>\n    <span class=\"n\">path</span><span class=\"p\">(</span><span class=\"s1\">&#39;about/&#39;</span><span class=\"p\">,</span> <span class=\"n\">AboutView</span><span class=\"o\">.</span><span class=\"n\">as_view</span><span class=\"p\">()),</span>\n<span class=\"p\">]</span>\n</code></pre></div>\n<p>For more information on how to use the built in generic views, consult the next\ntopic on <a class=\"reference internal\" href=\"/zh-hans/2.1/topics/class-based-views/generic-display/\"><span class=\"doc\">generic class-based views</span></a>.</p>\n<section id=\"supporting-other-http-methods\">\n<span id=\"id1\"></span><h3>Supporting other HTTP methods<a class=\"heading-anchor\" href=\"#supporting-other-http-methods\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Suppose somebody wants to access our book library over HTTP using the views\nas an API. The API client would connect every now and then and download book\ndata for the books published since last visit. But if no new books appeared\nsince then, it is a waste of CPU time and bandwidth to fetch the books from the\ndatabase, render a full response and send it to the client. It might be\npreferable to ask the API when the most recent book was published.</p>\n<p>We map the URL to book list view in the URLconf:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.urls</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">path</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">books.views</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">BookListView</span>\n\n<span class=\"n\">urlpatterns</span> <span class=\"o\">=</span> <span class=\"p\">[</span>\n    <span class=\"n\">path</span><span class=\"p\">(</span><span class=\"s1\">&#39;books/&#39;</span><span class=\"p\">,</span> <span class=\"n\">BookListView</span><span class=\"o\">.</span><span class=\"n\">as_view</span><span class=\"p\">()),</span>\n<span class=\"p\">]</span>\n</code></pre></div>\n<p>And the view:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.http</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">HttpResponse</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.views.generic</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">ListView</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">books.models</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">Book</span>\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">BookListView</span><span class=\"p\">(</span><span class=\"n\">ListView</span><span class=\"p\">):</span>\n    <span class=\"n\">model</span> <span class=\"o\">=</span> <span class=\"n\">Book</span>\n\n    <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">head</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"o\">*</span><span class=\"n\">args</span><span class=\"p\">,</span> <span class=\"o\">**</span><span class=\"n\">kwargs</span><span class=\"p\">):</span>\n        <span class=\"n\">last_book</span> <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">get_queryset</span><span class=\"p\">()</span><span class=\"o\">.</span><span class=\"n\">latest</span><span class=\"p\">(</span><span class=\"s1\">&#39;publication_date&#39;</span><span class=\"p\">)</span>\n        <span class=\"n\">response</span> <span class=\"o\">=</span> <span class=\"n\">HttpResponse</span><span class=\"p\">(</span><span class=\"s1\">&#39;&#39;</span><span class=\"p\">)</span>\n        <span class=\"c1\"># RFC 1123 date format</span>\n        <span class=\"n\">response</span><span class=\"p\">[</span><span class=\"s1\">&#39;Last-Modified&#39;</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"n\">last_book</span><span class=\"o\">.</span><span class=\"n\">publication_date</span><span class=\"o\">.</span><span class=\"n\">strftime</span><span class=\"p\">(</span><span class=\"s1\">&#39;</span><span class=\"si\">%a</span><span class=\"s1\">, </span><span class=\"si\">%d</span><span class=\"s1\"> %b %Y %H:%M:%S GMT&#39;</span><span class=\"p\">)</span>\n        <span class=\"k\">return</span> <span class=\"n\">response</span>\n</code></pre></div>\n<p>If the view is accessed from a <code class=\"docutils literal notranslate\"><span class=\"pre\">GET</span></code> request, a plain-and-simple object\nlist is returned in the response (using <code class=\"docutils literal notranslate\"><span class=\"pre\">book_list.html</span></code> template). But if\nthe client issues a <code class=\"docutils literal notranslate\"><span class=\"pre\">HEAD</span></code> request, the response has an empty body and\nthe <code class=\"docutils literal notranslate\"><span class=\"pre\">Last-Modified</span></code> header indicates when the most recent book was published.\nBased on this information, the client may or may not download the full object\nlist.</p>\n</section>\n</section>","rootId":"class-based-views","toc":[{"title":"Basic examples","anchor":"basic-examples","children":[]},{"title":"Simple usage in your URLconf","anchor":"simple-usage-in-your-urlconf","children":[]},{"title":"Subclassing generic views","anchor":"subclassing-generic-views","children":[{"title":"Supporting other HTTP methods","anchor":"supporting-other-http-methods","children":[]}]}],"breadcrumbs":[{"docname":"topics/index","title":"Using Django","url":"/zh-hans/2.1/topics/"}],"prev":{"docname":"topics/templates","title":"模板","url":"/zh-hans/2.1/topics/templates/"},"next":{"docname":"topics/class-based-views/intro","title":"基于类的视图","url":"/zh-hans/2.1/topics/class-based-views/intro/"},"formats":{"html":"/zh-hans/2.1/topics/class-based-views/","markdown":"/zh-hans/2.1/topics/class-based-views.md","json":"/zh-hans/2.1/topics/class-based-views.json"},"source":"https://github.com/django/django/blob/stable/2.1.x/docs/topics/class-based-views/index.txt","official":"https://docs.djangoproject.com/zh-hans/2.1/topics/class-based-views/","inVersions":["6.1","6.0","5.2","5.1","5.0","4.2","4.1","4.0","3.2","3.1","3.0","2.2","2.1","2.0"],"inLocales":["en","zh-hans","fr","ja","id","pt-br","ko","es","el","pl"]}