{"id":75715,"date":"2020-01-20T11:51:01","date_gmt":"2020-01-20T06:21:01","guid":{"rendered":"https:\/\/www.vskills.in\/certification\/tutorial\/?p=75715"},"modified":"2024-04-12T14:17:15","modified_gmt":"2024-04-12T08:47:15","slug":"extending-generic-views-2","status":"publish","type":"page","link":"https:\/\/www.vskills.in\/certification\/tutorial\/extending-generic-views-2\/","title":{"rendered":"Extending Generic Views"},"content":{"rendered":"<p>There\u2019s no question that using generic views can speed up development substantially. In most projects, however, there comes a moment when the generic views no longer suffice. Indeed, the most common question asked by new Django developers is how to make generic views handle a wider array of situations. Luckily, in nearly every one of these cases, there are ways to simply extend generic views to handle a larger array of use cases. These situations usually fall into a handful of patterns dealt with in the sections that follow.<\/p>\n<p><strong>Making \u201cFriendly\u201d Template Contexts<\/strong> &#8211; You might have noticed that sample publisher list template stores all the books 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 books here. A better name for that variable would be publisher_list; that variable\u2019s content is pretty obvious. We can change the name of that variable easily with the template_object_name argument:<\/p>\n<p>publisher_info = {<br>\n&#8220;queryset&#8221; : Publisher.objects.all(),<br>\n&#8220;template_object_name&#8221; : &#8220;publisher&#8221;,<br>\n}<br>\nurlpatterns = patterns(&#8221;,<br>\n(r&#8217;^publishers\/$&#8217;, list_detail.object_list, publisher_info)<br>\n)<\/p>\n<p>Providing a useful template_object_name is always a good idea. Your coworkers who design templates will thank you.<\/p>\n<p><strong>Adding Extra Context<\/strong> &#8211; 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 other publishers on each publisher detail page. The object_detail generic view provides the publisher to the context, but it seems there\u2019s no way to get a list of all publishers in that template. But there is: all generic views take an extra optional parameter, extra_context. This is a dictionary of extra objects that will be added to the template\u2019s context. So, to provide the list of all publishers on the detail detail view, we\u2019d use an info dict like this:<\/p>\n<p>publisher_info = {<br>\n&#8220;queryset&#8221; : Publisher.objects.all(),<br>\n&#8220;template_object_name&#8221; : &#8220;publisher&#8221;,<br>\n&#8220;extra_context&#8221; : {&#8220;book_list&#8221; : Book.objects.all()}<br>\n}<\/p>\n<p>This would populate a {{ book_list }} variable in the template context. This pattern can be used to pass any information down into the template for the generic view. It\u2019s very handy. However, there\u2019s actually a subtle bug here \u2014 can you spot it?<\/p>\n<p>The problem has to do with when the queries in extra_context are evaluated. Because this example puts Publisher.objects.all() in the URLconf, it will be evaluated only once (when the URLconf is first loaded). Once you add or remove publishers, you\u2019ll notice that the generic view doesn\u2019t reflect those changes until you reload the Web server<\/p>\n<p><strong>Note<\/strong> &#8211; This problem doesn\u2019t apply to the queryset generic view argument. Since Django knows that particular QuerySet should never be cached, the generic view takes care of clearing the cache when each view is rendered. The solution is to use a callback in extra_context instead of a value. Any callable (i.e., a function) that\u2019s passed to extra_context will be evaluated when the view is rendered (instead of only once). You could do this with an explicitly defined function:<\/p>\n<p>def get_books():<br>\nreturn Book.objects.all()<br>\npublisher_info = {<br>\n&#8220;queryset&#8221; : Publisher.objects.all(),<br>\n&#8220;template_object_name&#8221; : &#8220;publisher&#8221;,<br>\n&#8220;extra_context&#8221; : {&#8220;book_list&#8221; : get_books}<br>\n}<\/p>\n<p>or you could use a less obvious but shorter version that relies on the fact that<br>\nPublisher.objects.all is itself a callable:<br>\npublisher_info = {<br>\n&#8220;queryset&#8221; : Publisher.objects.all(),<br>\n&#8220;template_object_name&#8221; : &#8220;publisher&#8221;,<br>\n&#8220;extra_context&#8221; : {&#8220;book_list&#8221; : Book.objects.all}<br>\n}<\/p>\n<p>Notice the lack of parentheses after Book.objects.all; this references the function without actually calling it (which the generic view will do later).<\/p>\n<p><strong>Viewing Subsets of Objects<\/strong> &#8211; Now let\u2019s take a closer look at this queryset key we\u2019ve been using all along. Most generic views take one of these queryset arguments \u2014 it\u2019s how the view knows which set of objects to display. 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>book_info = {<br>\n&#8220;queryset&#8221; : Book.objects.all().order_by(&#8220;-publication_date&#8221;),<br>\n}<\/p>\n<p>urlpatterns = patterns(&#8221;,<br>\n(r&#8217;^publishers\/$&#8217;, list_detail.object_list, publisher_info),<br>\n(r&#8217;^books\/$&#8217;, list_detail.object_list, book_info),<br>\n)<\/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>apress_books = {<br>\n&#8220;queryset&#8221;: Book.objects.filter(publisher__name=&#8221;Apress Publishing&#8221;),<br>\n&#8220;template_name&#8221; : &#8220;books\/apress_list.html&#8221;<br>\n}<\/p>\n<p>urlpatterns = patterns(&#8221;,<br>\n(r&#8217;^publishers\/$&#8217;, list_detail.object_list, publisher_info),<br>\n(r&#8217;^books\/apress\/$&#8217;, list_detail.object_list, apress_books),<br>\n)<\/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. 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<p><strong>Note<\/strong> &#8211; If you get a 404 when requesting \/books\/apress\/, check to ensure you actually have a Publisher with the name \u2018Apress Publishing\u2019. Generic views have an allow_empty parameter for this case.<\/p>\n<p>Complex Filtering with Wrapper Functions &#8211; 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? We can \u201cwrap\u201d the object_list generic view to avoid writing a lot of code by hand. As usual, we\u2019ll start by writing a URLconf:<\/p>\n<p>urlpatterns = patterns(&#8221;,<br>\n(r&#8217;^publishers\/$&#8217;, list_detail.object_list, publisher_info),<br>\n(r&#8217;^books\/(w+)\/$&#8217;, books_by_publisher),<br>\n)<\/p>\n<p>Next, we\u2019ll write the books_by_publisher view itself:<\/p>\n<p>from django.http import Http404<br>\nfrom django.views.generic import list_detail<br>\nfrom mysite.books.models import Book, Publisher<\/p>\n<p>def books_by_publisher(request, name):<br>\n# Look up the publisher (and raise a 404 if it can&#8217;t be found).<br>\ntry:<br>\npublisher = Publisher.objects.get(name__iexact=name)<br>\nexcept Publisher.DoesNotExist:<br>\nraise Http404<\/p>\n<p># Use the object_list view for the heavy lifting.<br>\nreturn list_detail.object_list(<br>\nrequest,<br>\nqueryset = Book.objects.filter(publisher=publisher),<br>\ntemplate_name = &#8220;books\/books_by_publisher.html&#8221;,<br>\ntemplate_object_name = &#8220;books&#8221;,<br>\nextra_context = {&#8220;publisher&#8221; : publisher}<br>\n)<\/p>\n<p>This works because there\u2019s really nothing special about generic views \u2014 they\u2019re just Python functions. Like any view function, generic views expect a certain set of arguments and return HttpResponse objects. Thus, it\u2019s incredibly easy to wrap a small function around a generic view that does additional work before handing things off to the generic view.<\/p>\n<p><strong>Note<\/strong> &#8211; Notice that in the preceding example we passed the current publisher being displayed in the extra_context. This is usually a good idea in wrappers of this nature; it lets the template know which \u201cparent\u201d object is currently being browsed.<\/p>\n<p><strong>Performing Extra Work<\/strong> &#8211; 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 object that we were using to keep track of the last time anybody looked at that author. The generic object_detail view, 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 mysite.books.views import author_detail<\/p>\n<p>urlpatterns = patterns(&#8221;,<br>\n#&#8230;<br>\n(r&#8217;^authors\/(?P&lt;author_id&gt;d+)\/$&#8217;, author_detail),<br>\n)<\/p>\n<p>Then we\u2019d write our wrapper function:<\/p>\n<p>import datetime<br>\nfrom mysite.books.models import Author<br>\nfrom django.views.generic import list_detail<br>\nfrom django.shortcuts import get_object_or_404<\/p>\n<p>def author_detail(request, author_id):<br>\n# Look up the Author (and raise a 404 if she&#8217;s not found)<br>\nauthor = get_object_or_404(Author, pk=author_id)<\/p>\n<p># Record the last accessed date<br>\nauthor.last_accessed = datetime.datetime.now()<br>\nauthor.save()<\/p>\n<p># Show the detail page<br>\nreturn list_detail.object_detail(<br>\nrequest,<br>\nqueryset = Author.objects.all(),<br>\nobject_id = author_id,<br>\n)<\/p>\n<p>Note &#8211; This code won\u2019t actually work unless you add a last_accessed field to your Author model and create a books\/author_detail.html template.<\/p>\n<p>We can use a similar idiom to alter the response returned by the generic view. If we wanted to provide a downloadable plain-text version of the list of authors, we could use a view like this:<\/p>\n<p>def author_list_plaintext(request):<br>\nresponse = list_detail.object_list(<br>\nrequest,<br>\nqueryset = Author.objects.all(),<br>\nmimetype = &#8220;text\/plain&#8221;,<br>\ntemplate_name = &#8220;books\/author_list.txt&#8221;<br>\n)<br>\nresponse[&#8220;Content-Disposition&#8221;] = &#8220;attachment; filename=authors.txt&#8221;<br>\nreturn response<\/p>\n<p>This works because the generic views return simple HttpResponse objects that can be treated like dictionaries to set HTTP headers. This Content-Disposition business, by the way, instructs the browser to download and save the page instead of displaying it in the browser.<\/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>There\u2019s no question that using generic views can speed up development substantially. In most projects, however, there comes a moment when the generic views no longer suffice. Indeed, the most common question asked by new Django developers is how to make generic views handle a wider array of situations. Luckily, in nearly every one of&#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":[2628],"class_list":["post-75715","page","type-page","status-publish","hentry","category-django-web-development","tag-extending-generic-views"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Extending Generic Views - 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\/extending-generic-views-2\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Extending Generic Views - Tutorial\" \/>\n<meta property=\"og:description\" content=\"There\u2019s no question that using generic views can speed up development substantially. In most projects, however, there comes a moment when the generic views no longer suffice. Indeed, the most common question asked by new Django developers is how to make generic views handle a wider array of situations. Luckily, in nearly every one of...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.vskills.in\/certification\/tutorial\/extending-generic-views-2\/\" \/>\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=\"8 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\/extending-generic-views-2\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/extending-generic-views-2\/\",\"name\":\"Extending Generic Views - Tutorial\",\"isPartOf\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\"},\"datePublished\":\"2020-01-20T06:21:01+00:00\",\"dateModified\":\"2024-04-12T08:47:15+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/extending-generic-views-2\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.vskills.in\/certification\/tutorial\/extending-generic-views-2\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/extending-generic-views-2\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Extending Generic Views\"}]},{\"@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":"Extending Generic Views - 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\/extending-generic-views-2\/","og_locale":"en_US","og_type":"article","og_title":"Extending Generic Views - Tutorial","og_description":"There\u2019s no question that using generic views can speed up development substantially. In most projects, however, there comes a moment when the generic views no longer suffice. Indeed, the most common question asked by new Django developers is how to make generic views handle a wider array of situations. Luckily, in nearly every one of...","og_url":"https:\/\/www.vskills.in\/certification\/tutorial\/extending-generic-views-2\/","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":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/extending-generic-views-2\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/extending-generic-views-2\/","name":"Extending Generic Views - Tutorial","isPartOf":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website"},"datePublished":"2020-01-20T06:21:01+00:00","dateModified":"2024-04-12T08:47:15+00:00","breadcrumb":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/extending-generic-views-2\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.vskills.in\/certification\/tutorial\/extending-generic-views-2\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/extending-generic-views-2\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.vskills.in\/certification\/tutorial\/"},{"@type":"ListItem","position":2,"name":"Extending Generic Views"}]},{"@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\/75715","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=75715"}],"version-history":[{"count":4,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75715\/revisions"}],"predecessor-version":[{"id":83377,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75715\/revisions\/83377"}],"wp:attachment":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/media?parent=75715"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/categories?post=75715"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/tags?post=75715"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}