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