generic-display.txt 16 KB

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