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