class-based-views.txt 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. =========================
  2. Class-based generic views
  3. =========================
  4. .. versionadded:: 1.3
  5. .. note::
  6. Prior to Django 1.3, generic views were implemented as functions. The
  7. function-based implementation has been removed in favor of the
  8. class-based approach described here.
  9. Writing Web applications can be monotonous, because we repeat certain patterns
  10. again and again. Django tries to take away some of that monotony at the model
  11. and template layers, but Web developers also experience this boredom at the view
  12. level.
  13. Django's *generic views* were developed to ease that pain. They take certain
  14. common idioms and patterns found in view development and abstract them so that
  15. you can quickly write common views of data without having to write too much
  16. code.
  17. We can recognize certain common tasks, like displaying a list of objects, and
  18. write code that displays a list of *any* object. Then the model in question can
  19. be passed as an extra argument to the URLconf.
  20. Django ships with generic views to do the following:
  21. * Perform common "simple" tasks: redirect to a different page and
  22. render a given template.
  23. * Display list and detail pages for a single object. If we were creating an
  24. application to manage conferences then a ``TalkListView`` and a
  25. ``RegisteredUserListView`` would be examples of list views. A single
  26. talk page is an example of what we call a "detail" view.
  27. * Present date-based objects in year/month/day archive pages,
  28. associated detail, and "latest" pages.
  29. `The Django Weblog <https://www.djangoproject.com/weblog/>`_'s
  30. year, month, and day archives are built with these, as would be a typical
  31. newspaper's archives.
  32. * Allow users to create, update, and delete objects -- with or
  33. without authorization.
  34. Taken together, these views provide easy interfaces to perform the most common
  35. tasks developers encounter.
  36. Simple usage
  37. ============
  38. Class-based generic views (and any class-based views that inherit from
  39. the base classes Django provides) can be configured in two
  40. ways: subclassing, or passing in arguments directly in the URLconf.
  41. When you subclass a class-based view, you can override attributes
  42. (such as the ``template_name``) or methods (such as ``get_context_data``)
  43. in your subclass to provide new values or methods. Consider, for example,
  44. a view that just displays one template, ``about.html``. Django has a
  45. generic view to do this - :class:`~django.views.generic.base.TemplateView` -
  46. so we can just subclass it, and override the template name::
  47. # some_app/views.py
  48. from django.views.generic import TemplateView
  49. class AboutView(TemplateView):
  50. template_name = "about.html"
  51. Then, we just need to add this new view into our URLconf. As the class-based
  52. views themselves are classes, we point the URL to the ``as_view`` class method
  53. instead, which is the entry point for class-based views::
  54. # urls.py
  55. from django.conf.urls import patterns, url, include
  56. from some_app.views import AboutView
  57. urlpatterns = patterns('',
  58. (r'^about/', AboutView.as_view()),
  59. )
  60. Alternatively, if you're only changing a few simple attributes on a
  61. class-based view, you can simply pass the new attributes into the ``as_view``
  62. method call itself::
  63. from django.conf.urls import patterns, url, include
  64. from django.views.generic import TemplateView
  65. urlpatterns = patterns('',
  66. (r'^about/', TemplateView.as_view(template_name="about.html")),
  67. )
  68. A similar overriding pattern can be used for the ``url`` attribute on
  69. :class:`~django.views.generic.base.RedirectView`, another simple
  70. generic view.
  71. Generic views of objects
  72. ========================
  73. :class:`~django.views.generic.base.TemplateView` certainly is useful,
  74. but Django's generic views really shine when it comes to presenting
  75. views of your database content. Because it's such a common task,
  76. Django comes with a handful of built-in generic views that make
  77. generating list and detail views of objects incredibly easy.
  78. Let's take a look at one of these generic views: the "object list" view. We'll
  79. be using these models::
  80. # models.py
  81. from django.db import models
  82. class Publisher(models.Model):
  83. name = models.CharField(max_length=30)
  84. address = models.CharField(max_length=50)
  85. city = models.CharField(max_length=60)
  86. state_province = models.CharField(max_length=30)
  87. country = models.CharField(max_length=50)
  88. website = models.URLField()
  89. class Meta:
  90. ordering = ["-name"]
  91. def __unicode__(self):
  92. return self.name
  93. class Book(models.Model):
  94. title = models.CharField(max_length=100)
  95. authors = models.ManyToManyField('Author')
  96. publisher = models.ForeignKey(Publisher)
  97. publication_date = models.DateField()
  98. To build a list page of all publishers, we'd use a URLconf along these lines::
  99. from django.conf.urls import patterns, url, include
  100. from django.views.generic import ListView
  101. from books.models import Publisher
  102. urlpatterns = patterns('',
  103. (r'^publishers/$', ListView.as_view(
  104. model=Publisher,
  105. )),
  106. )
  107. That's all the Python code we need to write. We still need to write a template,
  108. however. We could explicitly tell the view which template to use
  109. by including a ``template_name`` key in the arguments to as_view, but in
  110. the absence of an explicit template Django will infer one from the object's
  111. name. In this case, the inferred template will be
  112. ``"books/publisher_list.html"`` -- the "books" part comes from the name of the
  113. app that defines the model, while the "publisher" bit is just the lowercased
  114. version of the model's name.
  115. .. note::
  116. Thus, when (for example) the :class:`django.template.loaders.app_directories.Loader`
  117. template loader is enabled in :setting:`TEMPLATE_LOADERS`, the template
  118. location would be::
  119. /path/to/project/books/templates/books/publisher_list.html
  120. .. highlightlang:: html+django
  121. This template will be rendered against a context containing a variable called
  122. ``object_list`` that contains all the publisher objects. A very simple template
  123. might look like the following::
  124. {% extends "base.html" %}
  125. {% block content %}
  126. <h2>Publishers</h2>
  127. <ul>
  128. {% for publisher in object_list %}
  129. <li>{{ publisher.name }}</li>
  130. {% endfor %}
  131. </ul>
  132. {% endblock %}
  133. That's really all there is to it. All the cool features of generic views come
  134. from changing the "info" dictionary passed to the generic view. The
  135. :doc:`generic views reference</ref/class-based-views>` documents all the generic
  136. views and their options in detail; the rest of this document will consider
  137. some of the common ways you might customize and extend generic views.
  138. Extending generic views
  139. =======================
  140. .. highlightlang:: python
  141. There's no question that using generic views can speed up development
  142. substantially. In most projects, however, there comes a moment when the
  143. generic views no longer suffice. Indeed, the most common question asked by new
  144. Django developers is how to make generic views handle a wider array of
  145. situations.
  146. This is one of the reasons generic views were redesigned for the 1.3 release -
  147. previously, they were just view functions with a bewildering array of options;
  148. now, rather than passing in a large amount of configuration in the URLconf,
  149. the recommended way to extend generic views is to subclass them, and override
  150. their attributes or methods.
  151. Making "friendly" template contexts
  152. -----------------------------------
  153. You might have noticed that our sample publisher list template stores
  154. all the publishers in a variable named ``object_list``. While this
  155. works just fine, it isn't all that "friendly" to template authors:
  156. they have to "just know" that they're dealing with publishers here.
  157. Well, if you're dealing with a model object, this is already done for
  158. you. When you are dealing with an object or queryset, Django is able
  159. to populate the context using the verbose name (or the plural verbose
  160. name, in the case of a list of objects) of the object being displayed.
  161. This is provided in addition to the default ``object_list`` entry, but
  162. contains exactly the same data.
  163. If the verbose name (or plural verbose name) still isn't a good match,
  164. you can manually set the name of the context variable. The
  165. ``context_object_name`` attribute on a generic view specifies the
  166. context variable to use. In this example, we'll override it in the
  167. URLconf, since it's a simple change:
  168. .. parsed-literal::
  169. urlpatterns = patterns('',
  170. (r'^publishers/$', ListView.as_view(
  171. model=Publisher,
  172. **context_object_name="publisher_list",**
  173. )),
  174. )
  175. Providing a useful ``context_object_name`` is always a good idea. Your
  176. coworkers who design templates will thank you.
  177. Adding extra context
  178. --------------------
  179. Often you simply need to present some extra information beyond that
  180. provided by the generic view. For example, think of showing a list of
  181. all the books on each publisher detail page. The
  182. :class:`~django.views.generic.detail.DetailView` generic view provides
  183. the publisher to the context, but it seems there's no way to get
  184. additional information in that template.
  185. However, there is; you can subclass
  186. :class:`~django.views.generic.detail.DetailView` and provide your own
  187. implementation of the ``get_context_data`` method. The default
  188. implementation of this that comes with
  189. :class:`~django.views.generic.detail.DetailView` simply adds in the
  190. object being displayed to the template, but you can override it to show
  191. more::
  192. from django.views.generic import DetailView
  193. from books.models import Publisher, Book
  194. class PublisherDetailView(DetailView):
  195. context_object_name = "publisher"
  196. model = Publisher
  197. def get_context_data(self, **kwargs):
  198. # Call the base implementation first to get a context
  199. context = super(PublisherDetailView, self).get_context_data(**kwargs)
  200. # Add in a QuerySet of all the books
  201. context['book_list'] = Book.objects.all()
  202. return context
  203. .. note::
  204. Generally, get_context_data will merge the context data of all parent classes
  205. with those of the current class. To preserve this behavior in your own classes
  206. where you want to alter the context, you should be sure to call
  207. get_context_data on the super class. When no two classes try to define the same
  208. key, this will give the expected results. However if any class attempts to
  209. override a key after parent classes have set it (after the call to super), any
  210. children of that class will also need to explictly set it after super if they
  211. want to be sure to override all parents.
  212. Viewing subsets of objects
  213. --------------------------
  214. Now let's take a closer look at the ``model`` argument we've been
  215. using all along. The ``model`` argument, which specifies the database
  216. model that the view will operate upon, is available on all the
  217. generic views that operate on a single object or a collection of
  218. objects. However, the ``model`` argument is not the only way to
  219. specify the objects that the view will operate upon -- you can also
  220. specify the list of objects using the ``queryset`` argument::
  221. from django.views.generic import DetailView
  222. from books.models import Publisher, Book
  223. class PublisherDetailView(DetailView):
  224. context_object_name = "publisher"
  225. queryset = Publisher.objects.all()
  226. Specifying ``model = Publisher`` is really just shorthand for saying
  227. ``queryset = Publisher.objects.all()``. However, by using ``queryset``
  228. to define a filtered list of objects you can be more specific about the
  229. objects that will be visible in the view (see :doc:`/topics/db/queries`
  230. for more information about :class:`QuerySet` objects, and see the
  231. :doc:`class-based views reference </ref/class-based-views>` for the complete
  232. details).
  233. To pick a simple example, we might want to order a list of books by
  234. publication date, with the most recent first::
  235. urlpatterns = patterns('',
  236. (r'^publishers/$', ListView.as_view(
  237. queryset=Publisher.objects.all(),
  238. context_object_name="publisher_list",
  239. )),
  240. (r'^books/$', ListView.as_view(
  241. queryset=Book.objects.order_by("-publication_date"),
  242. context_object_name="book_list",
  243. )),
  244. )
  245. That's a pretty simple example, but it illustrates the idea nicely. Of course,
  246. you'll usually want to do more than just reorder objects. If you want to
  247. present a list of books by a particular publisher, you can use the same
  248. technique (here, illustrated using subclassing rather than by passing arguments
  249. in the URLconf)::
  250. from django.views.generic import ListView
  251. from books.models import Book
  252. class AcmeBookListView(ListView):
  253. context_object_name = "book_list"
  254. queryset = Book.objects.filter(publisher__name="Acme Publishing")
  255. template_name = "books/acme_list.html"
  256. Notice that along with a filtered ``queryset``, we're also using a custom
  257. template name. If we didn't, the generic view would use the same template as the
  258. "vanilla" object list, which might not be what we want.
  259. Also notice that this isn't a very elegant way of doing publisher-specific
  260. books. If we want to add another publisher page, we'd need another handful of
  261. lines in the URLconf, and more than a few publishers would get unreasonable.
  262. We'll deal with this problem in the next section.
  263. .. note::
  264. If you get a 404 when requesting ``/books/acme/``, check to ensure you
  265. actually have a Publisher with the name 'ACME Publishing'. Generic
  266. views have an ``allow_empty`` parameter for this case. See the
  267. :doc:`class-based-views reference</ref/class-based-views>` for more details.
  268. Dynamic filtering
  269. -----------------
  270. Another common need is to filter down the objects given in a list page by some
  271. key in the URL. Earlier we hard-coded the publisher's name in the URLconf, but
  272. what if we wanted to write a view that displayed all the books by some arbitrary
  273. publisher?
  274. Handily, the ``ListView`` has a
  275. :meth:`~django.views.generic.detail.ListView.get_queryset` method we can
  276. override. Previously, it has just been returning the value of the ``queryset``
  277. attribute, but now we can add more logic.
  278. The key part to making this work is that when class-based views are called,
  279. various useful things are stored on ``self``; as well as the request
  280. (``self.request``) this includes the positional (``self.args``) and name-based
  281. (``self.kwargs``) arguments captured according to the URLconf.
  282. Here, we have a URLconf with a single captured group::
  283. from books.views import PublisherBookListView
  284. urlpatterns = patterns('',
  285. (r'^books/(\w+)/$', PublisherBookListView.as_view()),
  286. )
  287. Next, we'll write the ``PublisherBookListView`` view itself::
  288. from django.shortcuts import get_object_or_404
  289. from django.views.generic import ListView
  290. from books.models import Book, Publisher
  291. class PublisherBookListView(ListView):
  292. context_object_name = "book_list"
  293. template_name = "books/books_by_publisher.html"
  294. def get_queryset(self):
  295. publisher = get_object_or_404(Publisher, name__iexact=self.args[0])
  296. return Book.objects.filter(publisher=publisher)
  297. As you can see, it's quite easy to add more logic to the queryset selection;
  298. if we wanted, we could use ``self.request.user`` to filter using the current
  299. user, or other more complex logic.
  300. We can also add the publisher into the context at the same time, so we can
  301. use it in the template::
  302. class PublisherBookListView(ListView):
  303. context_object_name = "book_list"
  304. template_name = "books/books_by_publisher.html"
  305. def get_queryset(self):
  306. self.publisher = get_object_or_404(Publisher, name__iexact=self.args[0])
  307. return Book.objects.filter(publisher=self.publisher)
  308. def get_context_data(self, **kwargs):
  309. # Call the base implementation first to get a context
  310. context = super(PublisherBookListView, self).get_context_data(**kwargs)
  311. # Add in the publisher
  312. context['publisher'] = self.publisher
  313. return context
  314. Performing extra work
  315. ---------------------
  316. The last common pattern we'll look at involves doing some extra work before
  317. or after calling the generic view.
  318. Imagine we had a ``last_accessed`` field on our ``Author`` object that we were
  319. using to keep track of the last time anybody looked at that author::
  320. # models.py
  321. class Author(models.Model):
  322. salutation = models.CharField(max_length=10)
  323. first_name = models.CharField(max_length=30)
  324. last_name = models.CharField(max_length=40)
  325. email = models.EmailField()
  326. headshot = models.ImageField(upload_to='/tmp')
  327. last_accessed = models.DateTimeField()
  328. The generic ``DetailView`` class, of course, wouldn't know anything about this
  329. field, but once again we could easily write a custom view to keep that field
  330. updated.
  331. First, we'd need to add an author detail bit in the URLconf to point to a
  332. custom view:
  333. .. parsed-literal::
  334. from books.views import AuthorDetailView
  335. urlpatterns = patterns('',
  336. #...
  337. **(r'^authors/(?P<pk>\\d+)/$', AuthorDetailView.as_view()),**
  338. )
  339. Then we'd write our new view -- ``get_object`` is the method that retrieves the
  340. object -- so we simply override it and wrap the call::
  341. import datetime
  342. from books.models import Author
  343. from django.views.generic import DetailView
  344. from django.shortcuts import get_object_or_404
  345. class AuthorDetailView(DetailView):
  346. queryset = Author.objects.all()
  347. def get_object(self):
  348. # Call the superclass
  349. object = super(AuthorDetailView, self).get_object()
  350. # Record the last accessed date
  351. object.last_accessed = datetime.datetime.now()
  352. object.save()
  353. # Return the object
  354. return object
  355. .. note::
  356. This code won't actually work unless you create a
  357. ``books/author_detail.html`` template.
  358. .. note::
  359. The URLconf here uses the named group ``pk`` - this name is the default
  360. name that ``DetailView`` uses to find the value of the primary key used to
  361. filter the queryset.
  362. If you want to change it, you'll need to do your own ``get()`` call
  363. on ``self.queryset`` using the new named parameter from ``self.kwargs``.
  364. More than just HTML
  365. -------------------
  366. So far, we've been focusing on rendering templates to generate
  367. responses. However, that's not all generic views can do.
  368. Each generic view is composed out of a series of mixins, and each
  369. mixin contributes a little piece of the entire view. Some of these
  370. mixins -- such as
  371. :class:`~django.views.generic.base.TemplateResponseMixin` -- are
  372. specifically designed for rendering content to an HTML response using a
  373. template. However, you can write your own mixins that perform
  374. different rendering behavior.
  375. For example, a simple JSON mixin might look something like this::
  376. from django import http
  377. from django.utils import simplejson as json
  378. class JSONResponseMixin(object):
  379. def render_to_response(self, context):
  380. "Returns a JSON response containing 'context' as payload"
  381. return self.get_json_response(self.convert_context_to_json(context))
  382. def get_json_response(self, content, **httpresponse_kwargs):
  383. "Construct an `HttpResponse` object."
  384. return http.HttpResponse(content,
  385. content_type='application/json',
  386. **httpresponse_kwargs)
  387. def convert_context_to_json(self, context):
  388. "Convert the context dictionary into a JSON object"
  389. # Note: This is *EXTREMELY* naive; in reality, you'll need
  390. # to do much more complex handling to ensure that arbitrary
  391. # objects -- such as Django model instances or querysets
  392. # -- can be serialized as JSON.
  393. return json.dumps(context)
  394. Then, you could build a JSON-returning
  395. :class:`~django.views.generic.detail.DetailView` by mixing your
  396. :class:`JSONResponseMixin` with the
  397. :class:`~django.views.generic.detail.BaseDetailView` -- (the
  398. :class:`~django.views.generic.detail.DetailView` before template
  399. rendering behavior has been mixed in)::
  400. class JSONDetailView(JSONResponseMixin, BaseDetailView):
  401. pass
  402. This view can then be deployed in the same way as any other
  403. :class:`~django.views.generic.detail.DetailView`, with exactly the
  404. same behavior -- except for the format of the response.
  405. If you want to be really adventurous, you could even mix a
  406. :class:`~django.views.generic.detail.DetailView` subclass that is able
  407. to return *both* HTML and JSON content, depending on some property of
  408. the HTTP request, such as a query argument or a HTTP header. Just mix
  409. in both the :class:`JSONResponseMixin` and a
  410. :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`,
  411. and override the implementation of :func:`render_to_response()` to defer
  412. to the appropriate subclass depending on the type of response that the user
  413. requested::
  414. class HybridDetailView(JSONResponseMixin, SingleObjectTemplateResponseMixin, BaseDetailView):
  415. def render_to_response(self, context):
  416. # Look for a 'format=json' GET argument
  417. if self.request.GET.get('format','html') == 'json':
  418. return JSONResponseMixin.render_to_response(self, context)
  419. else:
  420. return SingleObjectTemplateResponseMixin.render_to_response(self, context)
  421. Because of the way that Python resolves method overloading, the local
  422. ``render_to_response()`` implementation will override the versions provided by
  423. :class:`JSONResponseMixin` and
  424. :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`.
  425. Decorating class-based views
  426. ============================
  427. .. highlightlang:: python
  428. The extension of class-based views isn't limited to using mixins. You
  429. can use also use decorators.
  430. Decorating in URLconf
  431. ---------------------
  432. The simplest way of decorating class-based views is to decorate the
  433. result of the :meth:`~django.views.generic.base.View.as_view` method.
  434. The easiest place to do this is in the URLconf where you deploy your
  435. view::
  436. from django.contrib.auth.decorators import login_required, permission_required
  437. from django.views.generic import TemplateView
  438. from .views import VoteView
  439. urlpatterns = patterns('',
  440. (r'^about/', login_required(TemplateView.as_view(template_name="secret.html"))),
  441. (r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())),
  442. )
  443. This approach applies the decorator on a per-instance basis. If you
  444. want every instance of a view to be decorated, you need to take a
  445. different approach.
  446. .. _decorating-class-based-views:
  447. Decorating the class
  448. --------------------
  449. To decorate every instance of a class-based view, you need to decorate
  450. the class definition itself. To do this you apply the decorator to the
  451. :meth:`~django.views.generic.base.View.dispatch` method of the class.
  452. A method on a class isn't quite the same as a standalone function, so
  453. you can't just apply a function decorator to the method -- you need to
  454. transform it into a method decorator first. The ``method_decorator``
  455. decorator transforms a function decorator into a method decorator so
  456. that it can be used on an instance method. For example::
  457. from django.contrib.auth.decorators import login_required
  458. from django.utils.decorators import method_decorator
  459. from django.views.generic import TemplateView
  460. class ProtectedView(TemplateView):
  461. template_name = 'secret.html'
  462. @method_decorator(login_required)
  463. def dispatch(self, *args, **kwargs):
  464. return super(ProtectedView, self).dispatch(*args, **kwargs)
  465. In this example, every instance of ``ProtectedView`` will have
  466. login protection.
  467. .. note::
  468. ``method_decorator`` passes ``*args`` and ``**kwargs``
  469. as parameters to the decorated method on the class. If your method
  470. does not accept a compatible set of parameters it will raise a
  471. ``TypeError`` exception.