Detailed explanation of function packaging in Django General View

Source: Internet
Author: User
This article mainly introduces function packaging in Django's general view. Django is the most popular Pythonweb development framework. For more information, see Use function packaging to process complex data filtering

Another common requirement is to filter data objects based on keywords in URLs. Previously, we hardcoded the publisher's name in URLconf, but if we want to use a view to display all the books of a specified publisher, what should we do? We can wrap general object_list views to avoid writing a lot of manual code. By convention, we start with configuring the URL:

urlpatterns = patterns('', (r'^publishers/$', list_detail.object_list, publisher_info), **(r'^books/(\w+)/$', books_by_publisher),**)

Next, we will write the View books_by_publisher:

from django.shortcuts import get_object_or_404from django.views.generic import list_detailfrom mysite.books.models import Book, Publisherdef books_by_publisher(request, name): # Look up the publisher (and raise a 404 if it can't be found). publisher = get_object_or_404(Publisher, name__iexact=name) # Use the object_list view for the heavy lifting. return list_detail.object_list(  request,  queryset = Book.objects.filter(publisher=publisher),  template_name = 'books/books_by_publisher.html',  template_object_name = 'book',  extra_context = {'publisher': publisher} )

There is no problem in writing this, because the general view is a Python function. Like other View functions, a common view accepts some parameters and returns the HttpResponse object. Therefore, you can do more by packing common view functions.

Note:

Note that in the previous example, the current publisher parameter is passed in extra_context.
Handle additional work

Let's take a look at the last common mode:

Imagine that we have a last_accessed field in the Author object. We use this field to record the last access to author. Of course, the general view object_detail cannot solve this problem, but we can still easily compile a custom View to update this field.

First, we need to set a new custom view in the URL configuration:

from mysite.books.views import author_detailurlpatterns = patterns('', # ... **(r'^authors/(?P\d+)/$', author_detail),** # ...)

Next, write the packaging function:

import datetimefrom django.shortcuts import get_object_or_404from django.views.generic import list_detailfrom mysite.books.models import Authordef author_detail(request, author_id): # Delegate to the generic view and get an HttpResponse. response = list_detail.object_detail(  request,  queryset = Author.objects.all(),  object_id = author_id, ) # Record the last accessed date. We do this *after* the call # to object_detail(), not before it, so that this won't be called # unless the Author actually exists. (If the author doesn't exist, # object_detail() will raise Http404, and we won't reach this point.) now = datetime.datetime.now() Author.objects.filter(id=author_id).update(last_accessed=now) return response

Note:

This code cannot really work unless you add the last_accessed field to your Author model and create the books/author_detail.html template.

We can use the same method to modify the returned values of a general view. If we want to provide an author list for the plain text version for download, we can use the following view:

def author_list_plaintext(request): response = list_detail.object_list(  request,  queryset = Author.objects.all(),  mimetype = 'text/plain',  template_name = 'books/author_list.txt' ) response["Content-Disposition"] = "attachment; filename=authors.txt" return response

This method works because the HttpResponse object returned by the general view can set the HTTP header like a dictionary. The Content-Disposition indicates that the browser downloads and saves the page, rather than displaying it in the browser.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.