class-based-views.txt 23 KB

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