generic-display.txt 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. .. _Generic views:
  2. =========================
  3. Class-based 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. * Display list and detail pages for a single object. If we were creating an
  18. application to manage conferences then a ``TalkListView`` and a
  19. ``RegisteredUserListView`` would be examples of list views. A single
  20. talk page is an example of what we call a "detail" view.
  21. * Present date-based objects in year/month/day archive pages,
  22. associated detail, and "latest" pages.
  23. * Allow users to create, update, and delete objects -- with or
  24. without authorization.
  25. Taken together, these views provide easy interfaces to perform the most common
  26. tasks developers encounter.
  27. Extending generic views
  28. =======================
  29. There's no question that using generic views can speed up development
  30. substantially. In most projects, however, there comes a moment when the
  31. generic views no longer suffice. Indeed, the most common question asked by new
  32. Django developers is how to make generic views handle a wider array of
  33. situations.
  34. This is one of the reasons generic views were redesigned for the 1.3 release -
  35. previously, they were just view functions with a bewildering array of options;
  36. now, rather than passing in a large amount of configuration in the URLconf,
  37. the recommended way to extend generic views is to subclass them, and override
  38. their attributes or methods.
  39. That said, generic views will have a limit. If you find you're struggling to
  40. implement your view as a subclass of a generic view, then you may find it more
  41. effective to write just the code you need, using your own class-based or
  42. functional views.
  43. More examples of generic views are available in some third party applications,
  44. or you could write your own as needed.
  45. Generic views of objects
  46. ========================
  47. :class:`~django.views.generic.base.TemplateView` certainly is useful, but
  48. Django's generic views really shine when it comes to presenting views of your
  49. database content. Because it's such a common task, Django comes with a handful
  50. of built-in generic views that make generating list and detail views of objects
  51. incredibly easy.
  52. Let's start by looking at some examples of showing a list of objects or an
  53. individual object.
  54. .. comment: link here to the other topic pages (form handling, date based, mixins)
  55. We'll be using these models::
  56. # models.py
  57. from django.db import models
  58. class Publisher(models.Model):
  59. name = models.CharField(max_length=30)
  60. address = models.CharField(max_length=50)
  61. city = models.CharField(max_length=60)
  62. state_province = models.CharField(max_length=30)
  63. country = models.CharField(max_length=50)
  64. website = models.URLField()
  65. class Meta:
  66. ordering = ["-name"]
  67. # On Python 3: def __str__(self):
  68. def __unicode__(self):
  69. return self.name
  70. class Author(models.Model):
  71. salutation = models.CharField(max_length=10)
  72. name = models.CharField(max_length=200)
  73. email = models.EmailField()
  74. headshot = models.ImageField(upload_to='author_headshots')
  75. # On Python 3: def __str__(self):
  76. def __unicode__(self):
  77. return self.name
  78. class Book(models.Model):
  79. title = models.CharField(max_length=100)
  80. authors = models.ManyToManyField('Author')
  81. publisher = models.ForeignKey(Publisher)
  82. publication_date = models.DateField()
  83. Now we need to define a view::
  84. # views.py
  85. from django.views.generic import ListView
  86. from books.models import Publisher
  87. class PublisherList(ListView):
  88. model = Publisher
  89. Finally hook that view into your urls::
  90. # urls.py
  91. from django.conf.urls import patterns, url
  92. from books.views import PublisherList
  93. urlpatterns = patterns('',
  94. url(r'^publishers/$', PublisherList.as_view()),
  95. )
  96. That's all the Python code we need to write. We still need to write a template,
  97. however. We could explicitly tell the view which template to use by adding a
  98. ``template_name`` attribute to the view, but in the absence of an explicit
  99. template Django will infer one from the object's name. In this case, the
  100. inferred template will be ``"books/publisher_list.html"`` -- the "books" part
  101. comes from the name of the app that defines the model, while the "publisher"
  102. bit is just the lowercased version of the model's name.
  103. .. note::
  104. Thus, when (for example) the
  105. :class:`django.template.loaders.app_directories.Loader` template loader is
  106. enabled in :setting:`TEMPLATE_LOADERS`, a template location could be:
  107. /path/to/project/books/templates/books/publisher_list.html
  108. This template will be rendered against a context containing a variable called
  109. ``object_list`` that contains all the publisher objects. A very simple template
  110. might look like the following:
  111. .. code-block:: html+django
  112. {% extends "base.html" %}
  113. {% block content %}
  114. <h2>Publishers</h2>
  115. <ul>
  116. {% for publisher in object_list %}
  117. <li>{{ publisher.name }}</li>
  118. {% endfor %}
  119. </ul>
  120. {% endblock %}
  121. That's really all there is to it. All the cool features of generic views come
  122. from changing the attributes set on the generic view. The
  123. :doc:`generic views reference</ref/class-based-views/index>` documents all the
  124. generic views and their options in detail; the rest of this document will
  125. consider some of the common ways you might customize and extend generic views.
  126. Making "friendly" template contexts
  127. -----------------------------------
  128. You might have noticed that our sample publisher list template stores all the
  129. publishers in a variable named ``object_list``. While this works just fine, it
  130. isn't all that "friendly" to template authors: they have to "just know" that
  131. they're dealing with publishers here.
  132. Well, if you're dealing with a model object, this is already done for you. When
  133. you are dealing with an object or queryset, Django is able to populate the
  134. context using the lower cased version of the model class' name. This is
  135. provided in addition to the default ``object_list`` entry, but contains exactly
  136. the same data, i.e. ``publisher_list``.
  137. If this still isn't a good match, you can manually set the name of the
  138. context variable. The ``context_object_name`` attribute on a generic view
  139. specifies the context variable to use::
  140. # views.py
  141. from django.views.generic import ListView
  142. from books.models import Publisher
  143. class PublisherList(ListView):
  144. model = Publisher
  145. context_object_name = 'my_favourite_publishers'
  146. Providing a useful ``context_object_name`` is always a good idea. Your
  147. coworkers who design templates will thank you.
  148. .. _adding-extra-context:
  149. Adding extra context
  150. --------------------
  151. Often you simply need to present some extra information beyond that
  152. provided by the generic view. For example, think of showing a list of
  153. all the books on each publisher detail page. The
  154. :class:`~django.views.generic.detail.DetailView` generic view provides
  155. the publisher to the context, but how do we get additional information
  156. in that template?
  157. The answer is to subclass :class:`~django.views.generic.detail.DetailView`
  158. and provide your own implementation of the ``get_context_data`` method.
  159. The default implementation simply adds the object being displayed to the
  160. template, but you can override it to send more::
  161. from django.views.generic import DetailView
  162. from books.models import Publisher, Book
  163. class PublisherDetail(DetailView):
  164. model = Publisher
  165. def get_context_data(self, **kwargs):
  166. # Call the base implementation first to get a context
  167. context = super(PublisherDetail, self).get_context_data(**kwargs)
  168. # Add in a QuerySet of all the books
  169. context['book_list'] = Book.objects.all()
  170. return context
  171. .. note::
  172. Generally, ``get_context_data`` will merge the context data of all parent
  173. classes with those of the current class. To preserve this behavior in your
  174. own classes where you want to alter the context, you should be sure to call
  175. ``get_context_data`` on the super class. When no two classes try to define the
  176. same key, this will give the expected results. However if any class
  177. attempts to override a key after parent classes have set it (after the call
  178. to super), any children of that class will also need to explicitly set it
  179. after super if they want to be sure to override all parents. If you're
  180. having trouble, review the method resolution order of your view.
  181. .. _generic-views-list-subsets:
  182. Viewing subsets of objects
  183. --------------------------
  184. Now let's take a closer look at the ``model`` argument we've been
  185. using all along. The ``model`` argument, which specifies the database
  186. model that the view will operate upon, is available on all the
  187. generic views that operate on a single object or a collection of
  188. objects. However, the ``model`` argument is not the only way to
  189. specify the objects that the view will operate upon -- you can also
  190. specify the list of objects using the ``queryset`` argument::
  191. from django.views.generic import DetailView
  192. from books.models import Publisher
  193. class PublisherDetail(DetailView):
  194. context_object_name = 'publisher'
  195. queryset = Publisher.objects.all()
  196. Specifying ``model = Publisher`` is really just shorthand for saying
  197. ``queryset = Publisher.objects.all()``. However, by using ``queryset``
  198. to define a filtered list of objects you can be more specific about the
  199. objects that will be visible in the view (see :doc:`/topics/db/queries`
  200. for more information about :class:`~django.db.models.query.QuerySet` objects,
  201. and see the :doc:`class-based views reference </ref/class-based-views/index>`
  202. for the complete details).
  203. To pick a simple example, we might want to order a list of books by
  204. publication date, with the most recent first::
  205. from django.views.generic import ListView
  206. from books.models import Book
  207. class BookList(ListView):
  208. queryset = Book.objects.order_by('-publication_date')
  209. context_object_name = 'book_list'
  210. That's a pretty simple example, but it illustrates the idea nicely. Of course,
  211. you'll usually want to do more than just reorder objects. If you want to
  212. present a list of books by a particular publisher, you can use the same
  213. technique::
  214. from django.views.generic import ListView
  215. from books.models import Book
  216. class AcmeBookList(ListView):
  217. context_object_name = 'book_list'
  218. queryset = Book.objects.filter(publisher__name='Acme Publishing')
  219. template_name = 'books/acme_list.html'
  220. Notice that along with a filtered ``queryset``, we're also using a custom
  221. template name. If we didn't, the generic view would use the same template as the
  222. "vanilla" object list, which might not be what we want.
  223. Also notice that this isn't a very elegant way of doing publisher-specific
  224. books. If we want to add another publisher page, we'd need another handful of
  225. lines in the URLconf, and more than a few publishers would get unreasonable.
  226. We'll deal with this problem in the next section.
  227. .. note::
  228. If you get a 404 when requesting ``/books/acme/``, check to ensure you
  229. actually have a Publisher with the name 'ACME Publishing'. Generic
  230. views have an ``allow_empty`` parameter for this case. See the
  231. :doc:`class-based-views reference</ref/class-based-views/index>` for more
  232. details.
  233. Dynamic filtering
  234. -----------------
  235. Another common need is to filter down the objects given in a list page by some
  236. key in the URL. Earlier we hard-coded the publisher's name in the URLconf, but
  237. what if we wanted to write a view that displayed all the books by some arbitrary
  238. publisher?
  239. Handily, the ``ListView`` has a
  240. :meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset` method we
  241. can override. Previously, it has just been returning the value of the
  242. ``queryset`` attribute, but now we can add more logic.
  243. The key part to making this work is that when class-based views are called,
  244. various useful things are stored on ``self``; as well as the request
  245. (``self.request``) this includes the positional (``self.args``) and name-based
  246. (``self.kwargs``) arguments captured according to the URLconf.
  247. Here, we have a URLconf with a single captured group::
  248. # urls.py
  249. from django.conf.urls import patterns
  250. from books.views import PublisherBookList
  251. urlpatterns = patterns('',
  252. (r'^books/([\w-]+)/$', PublisherBookList.as_view()),
  253. )
  254. Next, we'll write the ``PublisherBookList`` view itself::
  255. # views.py
  256. from django.shortcuts import get_object_or_404
  257. from django.views.generic import ListView
  258. from books.models import Book, Publisher
  259. class PublisherBookList(ListView):
  260. template_name = 'books/books_by_publisher.html'
  261. def get_queryset(self):
  262. self.publisher = get_object_or_404(Publisher, name=self.args[0])
  263. return Book.objects.filter(publisher=self.publisher)
  264. As you can see, it's quite easy to add more logic to the queryset selection;
  265. if we wanted, we could use ``self.request.user`` to filter using the current
  266. user, or other more complex logic.
  267. We can also add the publisher into the context at the same time, so we can
  268. use it in the template::
  269. # ...
  270. def get_context_data(self, **kwargs):
  271. # Call the base implementation first to get a context
  272. context = super(PublisherBookList, self).get_context_data(**kwargs)
  273. # Add in the publisher
  274. context['publisher'] = self.publisher
  275. return context
  276. .. _generic-views-extra-work:
  277. Performing extra work
  278. ---------------------
  279. The last common pattern we'll look at involves doing some extra work before
  280. or after calling the generic view.
  281. Imagine we had a ``last_accessed`` field on our ``Author`` model that we were
  282. using to keep track of the last time anybody looked at that author::
  283. # models.py
  284. from django.db import models
  285. class Author(models.Model):
  286. salutation = models.CharField(max_length=10)
  287. name = models.CharField(max_length=200)
  288. email = models.EmailField()
  289. headshot = models.ImageField(upload_to='author_headshots')
  290. last_accessed = models.DateTimeField()
  291. The generic ``DetailView`` class, of course, wouldn't know anything about this
  292. field, but once again we could easily write a custom view to keep that field
  293. updated.
  294. First, we'd need to add an author detail bit in the URLconf to point to a
  295. custom view::
  296. from django.conf.urls import patterns, url
  297. from books.views import AuthorDetailView
  298. urlpatterns = patterns('',
  299. #...
  300. url(r'^authors/(?P<pk>\d+)/$', AuthorDetailView.as_view(), name='author-detail'),
  301. )
  302. Then we'd write our new view -- ``get_object`` is the method that retrieves the
  303. object -- so we simply override it and wrap the call::
  304. from django.views.generic import DetailView
  305. from django.utils import timezone
  306. from books.models import Author
  307. class AuthorDetailView(DetailView):
  308. queryset = Author.objects.all()
  309. def get_object(self):
  310. # Call the superclass
  311. object = super(AuthorDetailView, self).get_object()
  312. # Record the last accessed date
  313. object.last_accessed = timezone.now()
  314. object.save()
  315. # Return the object
  316. return object
  317. .. note::
  318. The URLconf here uses the named group ``pk`` - this name is the default
  319. name that ``DetailView`` uses to find the value of the primary key used to
  320. filter the queryset.
  321. If you want to call the group something else, you can set ``pk_url_kwarg``
  322. on the view. More details can be found in the reference for
  323. :class:`~django.views.generic.detail.DetailView`