PageRenderTime 79ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

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