Debian Codegraph @

docs/topics/class-based-views/index.txt

raw
1 =================
2 Class-based views
3 =================
4
5 A view is a callable which takes a request and returns a
6 response. This can be more than just a function, and Django provides
7 an example of some classes which can be used as views. These allow you
8 to structure your views and reuse code by harnessing inheritance and
9 mixins. There are also some generic views for tasks which we'll get to later,
10 but you may want to design your own structure of reusable views which suits
11 your use case. For full details, see the :doc:`class-based views reference
12 documentation</ref/class-based-views/index>`.
13
14 .. toctree::
15 :maxdepth: 1
16
17 intro
18 generic-display
19 generic-editing
20 mixins
21
22 Basic examples
23 ==============
24
25 Django provides base view classes which will suit a wide range of applications.
26 All views inherit from the :class:`~django.views.generic.base.View` class, which
27 handles linking the view into the URLs, HTTP method dispatching and other
28 common features. :class:`~django.views.generic.base.RedirectView` provides a
29 HTTP redirect, and :class:`~django.views.generic.base.TemplateView` extends the
30 base class to make it also render a template.
31
32
33 Usage in your URLconf
34 =====================
35
36 The most direct way to use generic views is to create them directly in your
37 URLconf. If you're only changing a few attributes on a class-based view, you
38 can pass them into the :meth:`~django.views.generic.base.View.as_view` method
39 call itself::
40
41 from django.urls import path
42 from django.views.generic import TemplateView
43
44 urlpatterns = [
45 path("about/", TemplateView.as_view(template_name="about.html")),
46 ]
47
48 Any arguments passed to :meth:`~django.views.generic.base.View.as_view` will
49 override attributes set on the class. In this example, we set ``template_name``
50 on the ``TemplateView``. A similar overriding pattern can be used for the
51 ``url`` attribute on :class:`~django.views.generic.base.RedirectView`.
52
53
54 Subclassing generic views
55 =========================
56
57 The second, more powerful way to use generic views is to inherit from an
58 existing view and override attributes (such as the ``template_name``) or
59 methods (such as ``get_context_data``) in your subclass to provide new values
60 or methods. Consider, for example, a view that just displays one template,
61 ``about.html``. Django has a generic view to do this -
62 :class:`~django.views.generic.base.TemplateView` - so we can subclass it, and
63 override the template name::
64
65 # some_app/views.py
66 from django.views.generic import TemplateView
67
68
69 class AboutView(TemplateView):
70 template_name = "about.html"
71
72 Then we need to add this new view into our URLconf.
73 :class:`~django.views.generic.base.TemplateView` is a class, not a function, so
74 we point the URL to the :meth:`~django.views.generic.base.View.as_view` class
75 method instead, which provides a function-like entry to class-based views::
76
77 # urls.py
78 from django.urls import path
79 from some_app.views import AboutView
80
81 urlpatterns = [
82 path("about/", AboutView.as_view()),
83 ]
84
85
86 For more information on how to use the built in generic views, consult the next
87 topic on :doc:`generic class-based views</topics/class-based-views/generic-display>`.
88
89 .. _supporting-other-http-methods:
90
91 Supporting other HTTP methods
92 -----------------------------
93
94 Suppose somebody wants to access our book library over HTTP using the views
95 as an API. The API client would connect every now and then and download book
96 data for the books published since last visit. But if no new books appeared
97 since then, it is a waste of CPU time and bandwidth to fetch the books from the
98 database, render a full response and send it to the client. It might be
99 preferable to ask the API when the most recent book was published.
100
101 We map the URL to book list view in the URLconf::
102
103 from django.urls import path
104 from books.views import BookListView
105
106 urlpatterns = [
107 path("books/", BookListView.as_view()),
108 ]
109
110 And the view::
111
112 from django.http import HttpResponse
113 from django.views.generic import ListView
114 from books.models import Book
115
116
117 class BookListView(ListView):
118 model = Book
119
120 def head(self, *args, **kwargs):
121 last_book = self.get_queryset().latest("publication_date")
122 response = HttpResponse(
123 # RFC 1123 date format.
124 headers={
125 "Last-Modified": last_book.publication_date.strftime(
126 "%a, %d %b %Y %H:%M:%S GMT"
127 )
128 },
129 )
130 return response
131
132 If the view is accessed from a ``GET`` request, an object list is returned in
133 the response (using the ``book_list.html`` template). But if the client issues
134 a ``HEAD`` request, the response has an empty body and the ``Last-Modified``
135 header indicates when the most recent book was published. Based on this
136 information, the client may or may not download the full object list.
137
138 .. _async-class-based-views:
139
140 Asynchronous class-based views
141 ==============================
142
143 As well as the synchronous (``def``) method handlers already shown, ``View``
144 subclasses may define asynchronous (``async def``) method handlers to leverage
145 asynchronous code using ``await``::
146
147 import asyncio
148 from django.http import HttpResponse
149 from django.views import View
150
151
152 class AsyncView(View):
153 async def get(self, request, *args, **kwargs):
154 # Perform io-blocking view logic using await, sleep for example.
155 await asyncio.sleep(1)
156 return HttpResponse("Hello async world!")
157
158 Within a single view-class, all user-defined method handlers must be either
159 synchronous, using ``def``, or all asynchronous, using ``async def``. An
160 ``ImproperlyConfigured`` exception will be raised in ``as_view()`` if ``def``
161 and ``async def`` declarations are mixed.
162
163 Django will automatically detect asynchronous views and run them in an
164 asynchronous context. You can read more about Django's asynchronous support,
165 and how to best use async views, in :doc:`/topics/async`.