generic-views.txt 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. .. _topics-generic-views:
  2. =============
  3. Generic views
  4. =============
  5. Writing Web applications can be monotonous, because we repeat certain patterns
  6. again and again. Django tries to take away some of that monotony at the model
  7. and template layers, but Web developers also experience this boredom at the view
  8. level.
  9. Django's *generic views* were developed to ease that pain. They take certain
  10. common idioms and patterns found in view development and abstract them so that
  11. you can quickly write common views of data without having to write too much
  12. code.
  13. We can recognize certain common tasks, like displaying a list of objects, and
  14. write code that displays a list of *any* object. Then the model in question can
  15. be passed as an extra argument to the URLconf.
  16. Django ships with generic views to do the following:
  17. * Perform common "simple" tasks: redirect to a different page and
  18. render a given template.
  19. * Display list and detail pages for a single object. If we were creating an
  20. application to manage conferences then a ``talk_list`` view and a
  21. ``registered_user_list`` view would be examples of list views. A single
  22. talk page is an example of what we call a "detail" view.
  23. * Present date-based objects in year/month/day archive pages,
  24. associated detail, and "latest" pages. The Django Weblog's
  25. (http://www.djangoproject.com/weblog/) year, month, and
  26. day archives are built with these, as would be a typical
  27. newspaper's archives.
  28. * Allow users to create, update, and delete objects -- with or
  29. without authorization.
  30. Taken together, these views provide easy interfaces to perform the most common
  31. tasks developers encounter.
  32. Using generic views
  33. ===================
  34. All of these views are used by creating configuration dictionaries in
  35. your URLconf files and passing those dictionaries as the third member of the
  36. URLconf tuple for a given pattern.
  37. For example, here's a simple URLconf you could use to present a static "about"
  38. page::
  39. from django.conf.urls.defaults import *
  40. from django.views.generic.simple import direct_to_template
  41. urlpatterns = patterns('',
  42. ('^about/$', direct_to_template, {
  43. 'template': 'about.html'
  44. })
  45. )
  46. Though this might seem a bit "magical" at first glance -- look, a view with no
  47. code! --, actually the ``direct_to_template`` view simply grabs information from
  48. the extra-parameters dictionary and uses that information when rendering the
  49. view.
  50. Because this generic view -- and all the others -- is a regular view function
  51. like any other, we can reuse it inside our own views. As an example, let's
  52. extend our "about" example to map URLs of the form ``/about/<whatever>/`` to
  53. statically rendered ``about/<whatever>.html``. We'll do this by first modifying
  54. the URLconf to point to a view function:
  55. .. parsed-literal::
  56. from django.conf.urls.defaults import *
  57. from django.views.generic.simple import direct_to_template
  58. **from mysite.books.views import about_pages**
  59. urlpatterns = patterns('',
  60. ('^about/$', direct_to_template, {
  61. 'template': 'about.html'
  62. }),
  63. **('^about/(\w+)/$', about_pages),**
  64. )
  65. Next, we'll write the ``about_pages`` view::
  66. from django.http import Http404
  67. from django.template import TemplateDoesNotExist
  68. from django.views.generic.simple import direct_to_template
  69. def about_pages(request, page):
  70. try:
  71. return direct_to_template(request, template="about/%s.html" % page)
  72. except TemplateDoesNotExist:
  73. raise Http404()
  74. Here we're treating ``direct_to_template`` like any other function. Since it
  75. returns an ``HttpResponse``, we can simply return it as-is. The only slightly
  76. tricky business here is dealing with missing templates. We don't want a
  77. nonexistent template to cause a server error, so we catch
  78. ``TemplateDoesNotExist`` exceptions and return 404 errors instead.
  79. .. admonition:: Is there a security vulnerability here?
  80. Sharp-eyed readers may have noticed a possible security hole: we're
  81. constructing the template name using interpolated content from the browser
  82. (``template="about/%s.html" % page``). At first glance, this looks like a
  83. classic *directory traversal* vulnerability. But is it really?
  84. Not exactly. Yes, a maliciously crafted value of ``page`` could cause
  85. directory traversal, but although ``page`` *is* taken from the request URL,
  86. not every value will be accepted. The key is in the URLconf: we're using
  87. the regular expression ``\w+`` to match the ``page`` part of the URL, and
  88. ``\w`` only accepts letters and numbers. Thus, any malicious characters
  89. (dots and slashes, here) will be rejected by the URL resolver before they
  90. reach the view itself.
  91. Generic views of objects
  92. ========================
  93. The ``direct_to_template`` certainly is useful, but Django's generic views
  94. really shine when it comes to presenting views on your database content. Because
  95. it's such a common task, Django comes with a handful of built-in generic views
  96. that make generating list and detail views of objects incredibly easy.
  97. Let's take a look at one of these generic views: the "object list" view. We'll
  98. be using these models::
  99. # models.py
  100. from django.db import models
  101. class Publisher(models.Model):
  102. name = models.CharField(max_length=30)
  103. address = models.CharField(max_length=50)
  104. city = models.CharField(max_length=60)
  105. state_province = models.CharField(max_length=30)
  106. country = models.CharField(max_length=50)
  107. website = models.URLField()
  108. def __unicode__(self):
  109. return self.name
  110. class Meta:
  111. ordering = ["-name"]
  112. class Book(models.Model):
  113. title = models.CharField(max_length=100)
  114. authors = models.ManyToManyField('Author')
  115. publisher = models.ForeignKey(Publisher)
  116. publication_date = models.DateField()
  117. To build a list page of all publishers, we'd use a URLconf along these lines::
  118. from django.conf.urls.defaults import *
  119. from django.views.generic import list_detail
  120. from mysite.books.models import Publisher
  121. publisher_info = {
  122. "queryset" : Publisher.objects.all(),
  123. }
  124. urlpatterns = patterns('',
  125. (r'^publishers/$', list_detail.object_list, publisher_info)
  126. )
  127. That's all the Python code we need to write. We still need to write a template,
  128. however. We could explicitly tell the ``object_list`` view which template to use
  129. by including a ``template_name`` key in the extra arguments dictionary, but in
  130. the absence of an explicit template Django will infer one from the object's
  131. name. In this case, the inferred template will be
  132. ``"books/publisher_list.html"`` -- the "books" part comes from the name of the
  133. app that defines the model, while the "publisher" bit is just the lowercased
  134. version of the model's name.
  135. .. highlightlang:: html+django
  136. This template will be rendered against a context containing a variable called
  137. ``object_list`` that contains all the publisher objects. A very simple template
  138. might look like the following::
  139. {% extends "base.html" %}
  140. {% block content %}
  141. <h2>Publishers</h2>
  142. <ul>
  143. {% for publisher in object_list %}
  144. <li>{{ publisher.name }}</li>
  145. {% endfor %}
  146. </ul>
  147. {% endblock %}
  148. That's really all there is to it. All the cool features of generic views come
  149. from changing the "info" dictionary passed to the generic view. The
  150. :ref:`generic views reference<ref-generic-views>` documents all the generic
  151. views and all their options in detail; the rest of this document will consider
  152. some of the common ways you might customize and extend generic views.
  153. Extending generic views
  154. =======================
  155. .. highlightlang:: python
  156. There's no question that using generic views can speed up development
  157. substantially. In most projects, however, there comes a moment when the
  158. generic views no longer suffice. Indeed, the most common question asked by new
  159. Django developers is how to make generic views handle a wider array of
  160. situations.
  161. Luckily, in nearly every one of these cases, there are ways to simply extend
  162. generic views to handle a larger array of use cases. These situations usually
  163. fall into a handful of patterns dealt with in the sections that follow.
  164. Making "friendly" template contexts
  165. -----------------------------------
  166. You might have noticed that our sample publisher list template stores all the
  167. books in a variable named ``object_list``. While this works just fine, it isn't
  168. all that "friendly" to template authors: they have to "just know" that they're
  169. dealing with publishers here. A better name for that variable would be
  170. ``publisher_list``; that variable's content is pretty obvious.
  171. We can change the name of that variable easily with the ``template_object_name``
  172. argument:
  173. .. parsed-literal::
  174. publisher_info = {
  175. "queryset" : Publisher.objects.all(),
  176. **"template_object_name" : "publisher",**
  177. }
  178. urlpatterns = patterns('',
  179. (r'^publishers/$', list_detail.object_list, publisher_info)
  180. )
  181. Providing a useful ``template_object_name`` is always a good idea. Your
  182. coworkers who design templates will thank you.
  183. Adding extra context
  184. --------------------
  185. Often you simply need to present some extra information beyond that provided by
  186. the generic view. For example, think of showing a list of all the books on each
  187. publisher detail page. The ``object_detail`` generic view provides the
  188. publisher to the context, but it seems there's no way to get additional
  189. information in that template.
  190. But there is: all generic views take an extra optional parameter,
  191. ``extra_context``. This is a dictionary of extra objects that will be added to
  192. the template's context. So, to provide the list of all books on the detail
  193. detail view, we'd use an info dict like this:
  194. .. parsed-literal::
  195. from mysite.books.models import Publisher, **Book**
  196. publisher_info = {
  197. "queryset" : Publisher.objects.all(),
  198. "template_object_name" : "publisher",
  199. **"extra_context" : {"book_list" : Book.objects.all()}**
  200. }
  201. This would populate a ``{{ book_list }}`` variable in the template context.
  202. This pattern can be used to pass any information down into the template for the
  203. generic view. It's very handy.
  204. However, there's actually a subtle bug here -- can you spot it?
  205. The problem has to do with when the queries in ``extra_context`` are evaluated.
  206. Because this example puts ``Book.objects.all()`` in the URLconf, it will
  207. be evaluated only once (when the URLconf is first loaded). Once you add or
  208. remove books, you'll notice that the generic view doesn't reflect those
  209. changes until you reload the Web server (see :ref:`caching-and-querysets`
  210. for more information about when QuerySets are cached and evaluated).
  211. .. note::
  212. This problem doesn't apply to the ``queryset`` generic view argument. Since
  213. Django knows that particular QuerySet should *never* be cached, the generic
  214. view takes care of clearing the cache when each view is rendered.
  215. The solution is to use a callback in ``extra_context`` instead of a value. Any
  216. callable (i.e., a function) that's passed to ``extra_context`` will be evaluated
  217. when the view is rendered (instead of only once). You could do this with an
  218. explicitly defined function:
  219. .. parsed-literal::
  220. def get_books():
  221. return Book.objects.all()
  222. publisher_info = {
  223. "queryset" : Publisher.objects.all(),
  224. "template_object_name" : "publisher",
  225. "extra_context" : **{"book_list" : get_books}**
  226. }
  227. or you could use a less obvious but shorter version that relies on the fact that
  228. ``Book.objects.all`` is itself a callable:
  229. .. parsed-literal::
  230. publisher_info = {
  231. "queryset" : Publisher.objects.all(),
  232. "template_object_name" : "publisher",
  233. "extra_context" : **{"book_list" : Book.objects.all}**
  234. }
  235. Notice the lack of parentheses after ``Book.objects.all``; this references
  236. the function without actually calling it (which the generic view will do later).
  237. Viewing subsets of objects
  238. --------------------------
  239. Now let's take a closer look at this ``queryset`` key we've been using all
  240. along. Most generic views take one of these ``queryset`` arguments -- it's how
  241. the view knows which set of objects to display (see :ref:`topics-db-queries` for
  242. more information about ``QuerySet`` objects, and see the
  243. :ref:`generic views reference<ref-generic-views>` for the complete details).
  244. To pick a simple example, we might want to order a list of books by
  245. publication date, with the most recent first:
  246. .. parsed-literal::
  247. book_info = {
  248. "queryset" : Book.objects.all().order_by("-publication_date"),
  249. }
  250. urlpatterns = patterns('',
  251. (r'^publishers/$', list_detail.object_list, publisher_info),
  252. **(r'^books/$', list_detail.object_list, book_info),**
  253. )
  254. That's a pretty simple example, but it illustrates the idea nicely. Of course,
  255. you'll usually want to do more than just reorder objects. If you want to
  256. present a list of books by a particular publisher, you can use the same
  257. technique:
  258. .. parsed-literal::
  259. **acme_books = {**
  260. **"queryset": Book.objects.filter(publisher__name="Acme Publishing"),**
  261. **"template_name" : "books/acme_list.html"**
  262. **}**
  263. urlpatterns = patterns('',
  264. (r'^publishers/$', list_detail.object_list, publisher_info),
  265. **(r'^books/acme/$', list_detail.object_list, acme_books),**
  266. )
  267. Notice that along with a filtered ``queryset``, we're also using a custom
  268. template name. If we didn't, the generic view would use the same template as the
  269. "vanilla" object list, which might not be what we want.
  270. Also notice that this isn't a very elegant way of doing publisher-specific
  271. books. If we want to add another publisher page, we'd need another handful of
  272. lines in the URLconf, and more than a few publishers would get unreasonable.
  273. We'll deal with this problem in the next section.
  274. .. note::
  275. If you get a 404 when requesting ``/books/acme/``, check to ensure you
  276. actually have a Publisher with the name 'ACME Publishing'. Generic
  277. views have an ``allow_empty`` parameter for this case. See the
  278. :ref:`generic views reference<ref-generic-views>` for more details.
  279. Complex filtering with wrapper functions
  280. ----------------------------------------
  281. Another common need is to filter down the objects given in a list page by some
  282. key in the URL. Earlier we hard-coded the publisher's name in the URLconf, but
  283. what if we wanted to write a view that displayed all the books by some arbitrary
  284. publisher? We can "wrap" the ``object_list`` generic view to avoid writing a lot
  285. of code by hand. As usual, we'll start by writing a URLconf:
  286. .. parsed-literal::
  287. from mysite.books.views import books_by_publisher
  288. urlpatterns = patterns('',
  289. (r'^publishers/$', list_detail.object_list, publisher_info),
  290. **(r'^books/(\w+)/$', books_by_publisher),**
  291. )
  292. Next, we'll write the ``books_by_publisher`` view itself::
  293. from django.http import Http404
  294. from django.views.generic import list_detail
  295. from mysite.books.models import Book, Publisher
  296. def books_by_publisher(request, name):
  297. # Look up the publisher (and raise a 404 if it can't be found).
  298. try:
  299. publisher = Publisher.objects.get(name__iexact=name)
  300. except Publisher.DoesNotExist:
  301. raise Http404
  302. # Use the object_list view for the heavy lifting.
  303. return list_detail.object_list(
  304. request,
  305. queryset = Book.objects.filter(publisher=publisher),
  306. template_name = "books/books_by_publisher.html",
  307. template_object_name = "books",
  308. extra_context = {"publisher" : publisher}
  309. )
  310. This works because there's really nothing special about generic views -- they're
  311. just Python functions. Like any view function, generic views expect a certain
  312. set of arguments and return ``HttpResponse`` objects. Thus, it's incredibly easy
  313. to wrap a small function around a generic view that does additional work before
  314. (or after; see the next section) handing things off to the generic view.
  315. .. note::
  316. Notice that in the preceding example we passed the current publisher being
  317. displayed in the ``extra_context``. This is usually a good idea in wrappers
  318. of this nature; it lets the template know which "parent" object is currently
  319. being browsed.
  320. Performing extra work
  321. ---------------------
  322. The last common pattern we'll look at involves doing some extra work before
  323. or after calling the generic view.
  324. Imagine we had a ``last_accessed`` field on our ``Author`` object that we were
  325. using to keep track of the last time anybody looked at that author::
  326. # models.py
  327. class Author(models.Model):
  328. salutation = models.CharField(max_length=10)
  329. first_name = models.CharField(max_length=30)
  330. last_name = models.CharField(max_length=40)
  331. email = models.EmailField()
  332. headshot = models.ImageField(upload_to='/tmp')
  333. last_accessed = models.DateTimeField()
  334. The generic ``object_detail`` view, of course, wouldn't know anything about this
  335. field, but once again we could easily write a custom view to keep that field
  336. updated.
  337. First, we'd need to add an author detail bit in the URLconf to point to a
  338. custom view:
  339. .. parsed-literal::
  340. from mysite.books.views import author_detail
  341. urlpatterns = patterns('',
  342. #...
  343. **(r'^authors/(?P<author_id>\d+)/$', author_detail),**
  344. )
  345. Then we'd write our wrapper function::
  346. import datetime
  347. from mysite.books.models import Author
  348. from django.views.generic import list_detail
  349. from django.shortcuts import get_object_or_404
  350. def author_detail(request, author_id):
  351. # Look up the Author (and raise a 404 if she's not found)
  352. author = get_object_or_404(Author, pk=author_id)
  353. # Record the last accessed date
  354. author.last_accessed = datetime.datetime.now()
  355. author.save()
  356. # Show the detail page
  357. return list_detail.object_detail(
  358. request,
  359. queryset = Author.objects.all(),
  360. object_id = author_id,
  361. )
  362. .. note::
  363. This code won't actually work unless you create a
  364. ``books/author_detail.html`` template.
  365. We can use a similar idiom to alter the response returned by the generic view.
  366. If we wanted to provide a downloadable plain-text version of the list of
  367. authors, we could use a view like this::
  368. def author_list_plaintext(request):
  369. response = list_detail.object_list(
  370. request,
  371. queryset = Author.objects.all(),
  372. mimetype = "text/plain",
  373. template_name = "books/author_list.txt"
  374. )
  375. response["Content-Disposition"] = "attachment; filename=authors.txt"
  376. return response
  377. This works because the generic views return simple ``HttpResponse`` objects
  378. that can be treated like dictionaries to set HTTP headers. This
  379. ``Content-Disposition`` business, by the way, instructs the browser to
  380. download and save the page instead of displaying it in the browser.