{"id":75714,"date":"2020-01-20T11:50:51","date_gmt":"2020-01-20T06:20:51","guid":{"rendered":"https:\/\/www.vskills.in\/certification\/tutorial\/?p=75714"},"modified":"2024-04-12T14:17:15","modified_gmt":"2024-04-12T08:47:15","slug":"generic-views-of-objects","status":"publish","type":"page","link":"https:\/\/www.vskills.in\/certification\/tutorial\/generic-views-of-objects\/","title":{"rendered":"Generic Views of Objects"},"content":{"rendered":"<p>Django\u2019s generic views really shine when it comes to presenting views of your database content. Because it\u2019s such a common task, Django comes with a handful of built-in generic views that make generating list and detail views of objects incredibly easy.<\/p>\n<p>Let\u2019s start by looking at some examples of showing a list of objects or an individual object. We\u2019ll be using these models:<\/p>\n<p># models.py<br>\nfrom django.db import models<\/p>\n<p>class Publisher(models.Model):<br>\nname = models.CharField(max_length=30)<br>\naddress = models.CharField(max_length=50)<br>\ncity = models.CharField(max_length=60)<br>\nstate_province = models.CharField(max_length=30)<br>\ncountry = models.CharField(max_length=50)<br>\nwebsite = models.URLField()<\/p>\n<p>class Meta:<br>\nordering = [&#8220;-name&#8221;]\n<p>def __str__(self):<br>\nreturn self.name<\/p>\n<p>class Author(models.Model):<br>\nsalutation = models.CharField(max_length=10)<br>\nname = models.CharField(max_length=200)<br>\nemail = models.EmailField()<br>\nheadshot = models.ImageField(upload_to=&#8217;author_headshots&#8217;)<\/p>\n<p>def __str__(self):<br>\nreturn self.name<\/p>\n<p>class Book(models.Model):<br>\ntitle = models.CharField(max_length=100)<br>\nauthors = models.ManyToManyField(&#8216;Author&#8217;)<br>\npublisher = models.ForeignKey(Publisher)<br>\npublication_date = models.DateField()<\/p>\n<p>Now we need to define a view:<\/p>\n<p># views.py<br>\nfrom django.views.generic import ListView<br>\nfrom books.models import Publisher<\/p>\n<p>class PublisherList(ListView):<br>\nmodel = Publisher<\/p>\n<p>Finally hook that view into your urls:<\/p>\n<p># urls.py<br>\nfrom django.conf.urls import url<br>\nfrom books.views import PublisherList<\/p>\n<p>urlpatterns = [<br>\nurl(r&#8217;^publishers\/$&#8217;, PublisherList.as_view()),<br>\n]\n<p>That\u2019s all the Python code we need to write. We still need to write a template, however. We could explicitly tell the view which template to use by adding a template_name attribute to the view, but in the absence of an explicit template Django will infer one from the object\u2019s name. In this case, the inferred template will be books\/publisher_list.html \u2013 the \u201cbooks\u201d part comes from the name of the app that defines the model, while the \u201cpublisher\u201d bit is just the lowercased version of the model\u2019s name.<br>\nThus, when (for example) the APP_DIRS option of a DjangoTemplates backend is set to True in TEMPLATES, a template location could be: \/path\/to\/project\/books\/templates\/books\/publisher_list.html<\/p>\n<p>This template will be rendered against a context containing a variable called object_list that contains all the publisher objects. A very simple template might look like the following:<\/p>\n<p>{% extends &#8220;base.html&#8221; %}<\/p>\n<p>{% block content %}<br>\n&lt;h2&gt;Publishers&lt;\/h2&gt;<br>\n&lt;ul&gt;<br>\n{% for publisher in object_list %}<br>\n&lt;li&gt;{{ publisher.name }}&lt;\/li&gt;<br>\n{% endfor %}<br>\n&lt;\/ul&gt;<br>\n{% endblock %}<\/p>\n<p>That\u2019s really all there is to it. All the cool features of generic views come from changing the attributes set on the generic view. Appendix C documents all the generic views and their options in detail; the rest of this document will consider some of the common ways you might customize and extend generic views.<\/p>\n<h3>Making \u201cFriendly\u201d Template Contexts<\/h3>\n<p>You might have noticed that our sample publisher list template stores all the publishers in a variable named object_list. While this works just fine, it isn\u2019t all that \u201cfriendly\u201d to template authors: they have to \u201cjust know\u201d that they\u2019re dealing with publishers here.<\/p>\n<p>In Django, if you\u2019re dealing with a model object, this is already done for you. When you are dealing with an object or queryset, Django populates the context using the lower cased version of the model class\u2019 name. This is provided in addition to the default object_list entry, but contains exactly the same data, i.e. publisher_list.<\/p>\n<p>If this still isn\u2019t a good match, you can manually set the name of the context variable. The context_object_name attribute on a generic view specifies the context variable to use:<\/p>\n<p># views.py<br>\nfrom django.views.generic import ListView<br>\nfrom books.models import Publisher<\/p>\n<p>class PublisherList(ListView):<br>\nmodel = Publisher<br>\ncontext_object_name = &#8216;my_favorite_publishers&#8217;<\/p>\n<p>Providing a useful context_object_name is always a good idea. Your co-workers who design templates will thank you.<\/p>\n<p><strong>Adding Extra Context<\/strong><\/p>\n<p>Often you simply need to present some extra information beyond that provided by the generic view. For example, think of showing a list of all the books on each publisher detail page. The DetailView generic view provides the publisher to the context, but how do we get additional information in that template?<\/p>\n<p>The answer is to subclass DetailView and provide your own implementation of the get_context_data method. The default implementation simply adds the object being displayed to the template, but you can override it to send more:<\/p>\n<p>from django.views.generic import DetailView<br>\nfrom books.models import Publisher, Book<\/p>\n<p>class PublisherDetail(DetailView):<\/p>\n<p>model = Publisher<\/p>\n<p>def get_context_data(self, **kwargs):<br>\n# Call the base implementation first to get a context<br>\ncontext = super(PublisherDetail, self).get_context_data(**kwargs)<br>\n# Add in a QuerySet of all the books<br>\ncontext[&#8216;book_list&#8217;] = Book.objects.all()<br>\nreturn context<\/p>\n<h3>Viewing Subsets of Objects<\/h3>\n<p>Now let\u2019s take a closer look at the model argument we\u2019ve been using all along. The model argument, which specifies the database model that the view will operate upon, is available on all the generic views that operate on a single object or a collection of objects. However, the model argument is not the only way to specify the objects that the view will operate upon \u2013 you can also specify the list of objects using the queryset argument:<\/p>\n<p>from django.views.generic import DetailView<br>\nfrom books.models import Publisher<\/p>\n<p>class PublisherDetail(DetailView):<\/p>\n<p>context_object_name = &#8216;publisher&#8217;<br>\nqueryset = Publisher.objects.all()<\/p>\n<p>Specifying model = Publisher is really just shorthand for saying queryset = Publisher.objects.all(). However, by using queryset to define a filtered list of objects you can be more specific about the objects that will be visible in the view. To pick a simple example, we might want to order a list of books by publication date, with the most recent first:<\/p>\n<p>from django.views.generic import ListView<br>\nfrom books.models import Book<\/p>\n<p>class BookList(ListView):<br>\nqueryset = Book.objects.order_by(&#8216;-publication_date&#8217;)<br>\ncontext_object_name = &#8216;book_list&#8217;<\/p>\n<p>That\u2019s a pretty simple example, but it illustrates the idea nicely. Of course, you\u2019ll usually want to do more than just reorder objects. If you want to present a list of books by a particular publisher, you can use the same technique:<\/p>\n<p>from django.views.generic import ListView<br>\nfrom books.models import Book<\/p>\n<p>class AcmeBookList(ListView):<\/p>\n<p>context_object_name = &#8216;book_list&#8217;<br>\nqueryset = Book.objects.filter(publisher__name=&#8217;Acme Publishing&#8217;)<br>\ntemplate_name = &#8216;books\/acme_list.html&#8217;<\/p>\n<p>Notice that along with a filtered queryset, we\u2019re also using a custom template name. If we didn\u2019t, the generic view would use the same template as the \u201cvanilla\u201d object list, which might not be what we want.<\/p>\n<p>Also notice that this isn\u2019t a very elegant way of doing publisher-specific books. If we want to add another publisher page, we\u2019d need another handful of lines in the URLconf, and more than a few publishers would get unreasonable. We\u2019ll deal with this problem in the next section.<\/p>\n<h3>Dynamic Filtering<\/h3>\n<p>Another common need is to filter down the objects given in a list page by some key in the URL. Earlier we hard-coded the publisher\u2019s name in the URLconf, but what if we wanted to write a view that displayed all the books by some arbitrary publisher?<\/p>\n<p>Handily, the ListView has a get_queryset() method we can override. Previously, it has just been returning the value of the queryset attribute, but now we can add more logic. The key part to making this work is that when class-based views are called, various useful things are stored on self; as well as the request (self.request), this includes the positional (self.args) and name-based (self.kwargs) arguments captured according to the URLconf.<\/p>\n<p>Here, we have a URLconf with a single captured group:<\/p>\n<p># urls.py<br>\nfrom django.conf.urls import url<br>\nfrom books.views import PublisherBookList<\/p>\n<p>urlpatterns = [<br>\nurl(r&#8217;^books\/([\\w-]+)\/$&#8217;, PublisherBookList.as_view()),<br>\n]\n<p>Next, we\u2019ll write the PublisherBookList view itself:<\/p>\n<p># views.py<br>\nfrom django.shortcuts import get_object_or_404<br>\nfrom django.views.generic import ListView<br>\nfrom books.models import Book, Publisher<\/p>\n<p>class PublisherBookList(ListView):<\/p>\n<p>template_name = &#8216;books\/books_by_publisher.html&#8217;<\/p>\n<p>def get_queryset(self):<br>\nself.publisher = get_object_or_404(Publisher, name=self.args[0])<br>\nreturn Book.objects.filter(publisher=self.publisher)<\/p>\n<p>As you can see, it\u2019s quite easy to add more logic to the queryset selection; if we wanted, we could use self.request.user to filter using the current user, or other more complex logic. We can also add the publisher into the context at the same time, so we can use it in the template:<\/p>\n<p># &#8230;<\/p>\n<p>def get_context_data(self, **kwargs):<br>\n# Call the base implementation first to get a context<br>\ncontext = super(PublisherBookList, self).get_context_data(**kwargs)<\/p>\n<p># Add in the publisher<br>\ncontext[&#8216;publisher&#8217;] = self.publisher<br>\nreturn context ## Performing Extra Work<\/p>\n<p>The last common pattern we\u2019ll look at involves doing some extra work before or after calling the generic view. Imagine we had a last_accessed field on our Author model that we were using to keep track of the last time anybody looked at that author:<\/p>\n<p># models.py<br>\nfrom django.db import models<\/p>\n<p>class Author(models.Model):<br>\nsalutation = models.CharField(max_length=10)<br>\nname = models.CharField(max_length=200)<br>\nemail = models.EmailField()<br>\nheadshot = models.ImageField(upload_to=&#8217;author_headshots&#8217;)<br>\nlast_accessed = models.DateTimeField()<\/p>\n<p>The generic DetailView class, of course, wouldn\u2019t know anything about this field, but once again we could easily write a custom view to keep that field updated. First, we\u2019d need to add an author detail bit in the URLconf to point to a custom view:<\/p>\n<p>from django.conf.urls import url<br>\nfrom books.views import AuthorDetailView<\/p>\n<p>urlpatterns = [<br>\n#&#8230;<br>\nurl(r&#8217;^authors\/(?P&lt;pk&gt;[0-9]+)\/$&#8217;, AuthorDetailView.as_view(), name=&#8217;author-detail\\<br>\n&#8216;),<br>\n]\n<p>Then we\u2019d write our new view \u2013 get_object is the method that retrieves the object \u2013 so we simply override it and wrap the call:<\/p>\n<p>from django.views.generic import DetailView<br>\nfrom django.utils import timezone<br>\nfrom books.models import Author<\/p>\n<p>class AuthorDetailView(DetailView):<\/p>\n<p>queryset = Author.objects.all()<\/p>\n<p>def get_object(self):<br>\n# Call the superclass<br>\nobject = super(AuthorDetailView, self).get_object()<\/p>\n<p># Record the last accessed date<br>\nobject.last_accessed = timezone.now()<br>\nobject.save()<br>\n# Return the object<br>\nreturn object<\/p>\n<p>The URLconf here uses the named group pk \u2013 this name is the default name that DetailView uses to find the value of the primary key used to filter the queryset.<\/p>\n<p>If you want to call the group something else, you can set pk_url_kwarg on the view. More details can be found in the reference for DetailView.<\/p>\n\n\n<p><a href=\"https:\/\/www.vskills.in\/certification\/tutorial\/certified-django-developer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Back to Tutorial<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Django\u2019s generic views really shine when it comes to presenting views of your database content. Because it\u2019s such a common task, Django comes with a handful of built-in generic views that make generating list and detail views of objects incredibly easy. Let\u2019s start by looking at some examples of showing a list of objects or&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"categories":[8655],"tags":[8784],"class_list":["post-75714","page","type-page","status-publish","hentry","category-django-web-development","tag-generic-views-of-objects"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Generic Views of Objects - Tutorial<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.vskills.in\/certification\/tutorial\/generic-views-of-objects\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Generic Views of Objects - Tutorial\" \/>\n<meta property=\"og:description\" content=\"Django\u2019s generic views really shine when it comes to presenting views of your database content. Because it\u2019s such a common task, Django comes with a handful of built-in generic views that make generating list and detail views of objects incredibly easy. Let\u2019s start by looking at some examples of showing a list of objects or...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.vskills.in\/certification\/tutorial\/generic-views-of-objects\/\" \/>\n<meta property=\"og:site_name\" content=\"Tutorial\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/vskills.in\/\" \/>\n<meta property=\"article:modified_time\" content=\"2024-04-12T08:47:15+00:00\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"9 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/generic-views-of-objects\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/generic-views-of-objects\/\",\"name\":\"Generic Views of Objects - Tutorial\",\"isPartOf\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\"},\"datePublished\":\"2020-01-20T06:20:51+00:00\",\"dateModified\":\"2024-04-12T08:47:15+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/generic-views-of-objects\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.vskills.in\/certification\/tutorial\/generic-views-of-objects\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/generic-views-of-objects\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Generic Views of Objects\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"name\":\"Tutorial\",\"description\":\"Vskills - A initiative in elearning and certification\",\"publisher\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\",\"name\":\"Vskills\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"contentUrl\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"width\":73,\"height\":55,\"caption\":\"Vskills\"},\"image\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/vskills.in\/\",\"https:\/\/x.com\/vskills_in\",\"https:\/\/www.linkedin.com\/company-beta\/1371554\/\",\"https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Generic Views of Objects - Tutorial","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.vskills.in\/certification\/tutorial\/generic-views-of-objects\/","og_locale":"en_US","og_type":"article","og_title":"Generic Views of Objects - Tutorial","og_description":"Django\u2019s generic views really shine when it comes to presenting views of your database content. Because it\u2019s such a common task, Django comes with a handful of built-in generic views that make generating list and detail views of objects incredibly easy. Let\u2019s start by looking at some examples of showing a list of objects or...","og_url":"https:\/\/www.vskills.in\/certification\/tutorial\/generic-views-of-objects\/","og_site_name":"Tutorial","article_publisher":"https:\/\/www.facebook.com\/vskills.in\/","article_modified_time":"2024-04-12T08:47:15+00:00","twitter_misc":{"Est. reading time":"9 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/generic-views-of-objects\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/generic-views-of-objects\/","name":"Generic Views of Objects - Tutorial","isPartOf":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website"},"datePublished":"2020-01-20T06:20:51+00:00","dateModified":"2024-04-12T08:47:15+00:00","breadcrumb":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/generic-views-of-objects\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.vskills.in\/certification\/tutorial\/generic-views-of-objects\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/generic-views-of-objects\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.vskills.in\/certification\/tutorial\/"},{"@type":"ListItem","position":2,"name":"Generic Views of Objects"}]},{"@type":"WebSite","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","name":"Tutorial","description":"Vskills - A initiative in elearning and certification","publisher":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization","name":"Vskills","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","contentUrl":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","width":73,"height":55,"caption":"Vskills"},"image":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/vskills.in\/","https:\/\/x.com\/vskills_in","https:\/\/www.linkedin.com\/company-beta\/1371554\/","https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw"]}]}},"_links":{"self":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75714","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/comments?post=75714"}],"version-history":[{"count":4,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75714\/revisions"}],"predecessor-version":[{"id":83375,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75714\/revisions\/83375"}],"wp:attachment":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/media?parent=75714"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/categories?post=75714"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/tags?post=75714"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}