Home > Articles

This chapter is from the book

This chapter is from the book

5.9 Class-Based Views

Any Python callable that accepts an HttpRequest object as argument and returns an HttpResponse object is deemed a view in Django. So far, we’ve stuck exclusively to using Python functions to create views. Prior to Django 1.3, this was the only recommended way to create views. However, starting in version 1.3, Django introduced a class to allow developers to create view objects.

Django introduced a class to create view objects because coding the class for the view is actually rather tricky and prone to security issues. For this reason, despite the ability to use any Python callable as a view, developers stick to using the Django recommended class or else simply use functions.

The class itself is simply called View, and developers refer to classes that inherit View as class-based views (CBVs). These classes behave exactly like function views but come with several unexpected benefits.

To begin, let’s replace our Post list function view with a class-based view. Example 5.56 shows our current view.

Example 5.56: Project Code

blog/views.py in cb5dd59383

19  def post_list(request):
20      return render(
21          request,
22          'blog/post_list.html',
23          {'post_list': Post.objects.all()})

We are not going to change the logic of the function. However, the function must become a method belonging to a class (which implies the addition of the self parameter, required for Python methods). We may name the class whatever we wish, so we shall call it PostList, but for reasons discussed shortly, the name of the method must be get(), as shown in Example 5.57.

Example 5.57: Project Code

blog/views.py in d9b8e788d5

 3  from django.views.generic import View
 .      ...
20  class PostList(View):
21
22      def get(self, request):
23          return render(
24              request,
25              'blog/post_list.html',
26              {'post_list': Post.objects.all()})

The import of View typically causes beginners confusion because it implies that View is generic, leading people to confuse View and class-based views with generic class-based views (GCBVs). GCBVs are not the same as CBVs, and making a distinction between the two is crucial. We wait until Chapter 17 and Chapter 18 to deal with GCBVs. For the moment, know that we are building CBVs and that they are different from GCBVs.

Our PostList class inherits from the View class we imported, imbuing it with (currently unseen) behavior.

The significance of the name of the method get() is that it refers to the HTTP method used to access it (a primer on HTTP methods is provided in Appendix A). Therefore, our method will be called only if the user’s browser issues an HTTP GET request to a URL that is matched by our URL pattern. To contrast, if an HTTP POST request is made, Django will attempt to call the post() method, which will result in an error because we have not programmed such a method. We’ll come back to this shortly.

In /blog/urls.py, import the PostList class and then change the URL pattern pointer to the pattern shown in Example 5.58.

Example 5.58: Project Code

blog/urls.py in d9b8e788d5

3  from .views import PostList, post_detail
.      ...
.  urlpatterns = [
.      ...
.      url(r'^$',
.          PostList.as_view(),
.          name='blog_post_list'),
.      ...
.  ]

The as_view() method is provided by the inheritance of the View superclass and ensures that the proper method in our CBV is called. When Django receives an HTTP GET request to a URL that matches the regular expression in our URL pattern, as_view() will direct Django to the get() method we programmed. We’ll take a much closer look at exactly how shortly.

5.9.1 Comparing Class-Based Views to Functions Views

A CBV can do everything a function view can do. We’ve not seen the use of the URL pattern dictionary previously, and so we’ll now take the opportunity to use a dictionary in both a function view and a CBV to demonstrate similarities. The practical purpose of our dictionary is to override the base template of our view (which we defined in Chapter 4 in the template as parent_template), and the learning purpose is to familiarize you with the URL pattern dictionary and CBVs.

To start, we add the dictionary to both blog URL patterns, as shown in Example 5.59.

Example 5.59: Project Code

blog/urls.py in d3030ee8d3

 5  urlpatterns = [
 6      url(r'^$',
 7          PostList.as_view(),
 8          {'parent_template': 'base.html'},
 9          name='blog_post_list'),
10      url(r'^(?P<year>\d{4})/'
11          r'(?P<month>\d{1,2})/'
12          r'(?P<slug>[\w\-]+)/$',
13          post_detail,
14          {'parent_template': 'base.html'},
15          name='blog_post_detail'),
16  ]

In our post_detail function view, shown in Example 5.60, we must add a named parameter that’s the same as the key in the dictionary (if we had several keys, we’d add several parameters).

Example 5.60: Project Code

blog/views.py in d3030ee8d3

8   def post_detail(request, year, month,
9                   slug, parent_template=None):

To follow through with our example, we need to pass the argument to our template. In Example 5.61, we add parent_template to the context dictionary defined in the render() shortcut.

Example 5.61: Project Code

blog/views.py in d3030ee8d3

15     return render(
16         request,
17         'blog/post_detail.html',
18         {'post': post,
19          'parent_template': parent_template})

The process for using the dictionary is almost identical to a CBV. We first add a new parameter to the get() method and then pass the new argument to render(), as shown in Example 5.62.

Example 5.62: Project Code

blog/views.py in d3030ee8d3

22  class PostList(View):
23
24      def get(self, request, parent_template=None):
25          return render(
26              request,
27              'blog/post_list.html',
28              {'post_list': Post.objects.all(),
29               'parent_template': parent_template})

The modification illustrates a key point with CBVs: the view is entirely encapsulated by the class methods. The CBV is a container for multiple views, organized according to HTTP methods. At the moment, illustrating this more directly is impossible, but we revisit the concept in depth in Chapter 9. The bottom line at the moment is that any modification you might make to a function view occurs at the method level of a CBV.

We’re not actually interested in overriding the base templates of our views and so should revert the few changes we’ve made in this section.

5.9.2 Advantages of Class-Based Views

The key advantages and disadvantages of CBVs over function views are exactly the same advantages and disadvantages that classes and objects have over functions: encapsulating data and behavior is typically more intuitive but can easily grow in complexity, which comes at the cost of functional purity.

A staple of object-oriented programming (OOP) is the use of instance variables, typically referred to as attributes in Python. For instance, we can usually better adhere to DRY in classes by defining important values as attributes. In PostList, we replace the string in render() with an attribute (which contains the same value), as shown in Example 5.63.

Example 5.63: Project Code

blog/views.py in ac3db8b26b

20  class PostList(View):
21      template_name = 'blog/post_list.html'
22
23      def get(self, request):
24          return render(
25              request,
26              self.template_name,
27              {'post_list': Post.objects.all()})

At the moment, this does us little good on the DRY side of things, but it does offer us a level of control that function views do not offer. Quite powerfully, CBVs allow for existing class attributes to be overridden by values passed to as_view(). Should we wish to change the value of the template_name class attribute, for example, we need only pass it as a named argument to as_view() in the blog_post_list URL pattern, as shown in Example 5.64.

Example 5.64: Project Code

blog/urls.py in 78947978fd

6     url(r'^$',
7         PostList.as_view(
8             template_name='blog/post_list.html'),
9         name='blog_post_list'),

Even if the template_name attribute is unset, the view will still work as expected because of the value passed to as_view(), as shown in Example 5.65.

Example 5.65: Project Code

blog/views.py in 78947978fd

20   class PostList(View):
21       template_name = ''

However, if the template_name attribute is undefined (we never set it in the class definition), then as_view will ignore it.

In the event that template_name is unset and the developer forgets to pass it, we should be raising an ImproperlyConfigured exception. We will see its use in Chapter 17.

Once again, we’re not actually interested in the advantages presented by the changes made in this section, and so I will revert all of the changes made here in the project code.

5.9.3 View Internals

CBVs also come with several much subtler advantages. To best understand these advantages, it’s worth diving into the internals of View and seeing exactly what we’re inheriting when we create a CBV.

The easiest place to start is with as_view(). In a URL pattern, we use as_view() to reference the CBV. Example 5.66 shows an example generic URL pattern.

Example 5.66: Python Code

url(r'^(?P<slug>[\w\-]+)/$',
    CBV.as_view(class_attribute=some_value),
    {'dict_key': 'dict_value'},
    name='app_model_action')

The as_view() method is a static class method (note that we call PostList.as_view() and not PostList().as_view()) and acts as a factory; as_view() returns a view (a method on the instance of PostList). Its main purpose is to define a (nested) function that acts as an intermediary view: it receives all the data, figures out which CBV method to call (using the HTTP method), and then passes all the data to that method, as shown in Example 5.67.

Example 5.67: Python Code

# grossly simplified for your benefit
@classonlymethod
def as_view(cls, **initkwargs)
    def view(request, *args, **kwargs)
        # magic!
    return view

In Example 5.67, the cls parameter will be the CBV. In our blog_post_list URL pattern, as_view() will be called with cls set to PostList. When we passed template_name to as_view() in blog_post_list, initkwargs received a dictionary in which template_name was a key. Example 5.68 shows the result.

Example 5.68: Python Code

as_view(
    cls=PostList,
    initkwargs={
        'template_name': 'blog/post_list.html',
    })

To best behave like a view, the nested view() method first instantiates the CBV as the self variable (demonstrating exactly how flexible Python is as a language). The view() method then sets a few attributes (removed from the example code) and calls the dispatch() method on the newly instantiated object, as shown in Example 5.69.

Example 5.69: Python Code

# still quite simplified
@classonlymethod
def as_view(cls, **initkwargs)
    def view(request, *args, **kwargs)
        self = cls(**initkwargs)
        ...
        return self.dispatch(request, *args, **kwargs)
    return view

For clarity’s sake, I want to reiterate that passing undefined attributes to as_view() will result in problems because as_view() specifically checks for the existence of these attributes and raises an TypeError if it cannot find the attribute, as shown in Example 5.70.

Example 5.70: Python Code

# still quite simplified
@classonlymethod
def as_view(cls, **initkwargs)
    for key in initkwargs:
        ...
        if not hasattr(cls, key):
             raise TypeError(...)
    def view(request, *args, **kwargs)
        self = cls(**initkwargs)
        ...
        return self.dispatch(request, *args, **kwargs)
    return view

If as_view() is the heart of View, then dispatch() is the brain. The dispatch() method, returned by view(), is actually where the class figures out which method to use. dispatch() anticipates the following developer-defined methods: get(), post(), put(), patch(), delete(), head(), options(), trace(). In our PostList example, we defined a get() method. If a get() method is defined, View will automatically provide a head() method based on the get() method. In all cases, View implements an options() method for us (the HTTP OPTIONS method is used to see which methods are valid at that path).

In the event the CBV receives a request for a method that is not implemented, then dispatch() will call the http_method_not_allowed() method, which simply returns an HttpResponseNotAllowed object. The HttpResponseNotAllowed class is a subclass of HttpResponse and raises an HTTP 405 “Method Not Allowed” code, informing the user that that HTTP method is not handled by this path.

This behavior is subtle but very important: by default, function views are not technically compliant with HTTP methods. At the moment, all of our views are programmed to handle GET requests, the most basic of requests. However, if someone were to issue a PUT or TRACE request to our pages, only the PostList CBV will behave correctly by raising a 405 error. All of the other views (function views) will behave as if a GET request had been issued.

If we wanted, we could use the require_http_methods function decorator to set which HTTP methods are allowed on each of our function views. The decorator works as you might expect: you tell it which HTTP methods are valid, and any request with other methods will return an HTTP 405 error. For example, to limit the use of GET and HEAD methods on our Post detail view, we can add the decorator, as demonstrated in Example 5.71.

Example 5.71: Project Code

blog/views.py in 34baa4dfc3

 3  from django.views.decorators.http import  4      require_http_methods
 .      ...
10  @require_http_methods(['HEAD', 'GET'])
11  def post_detail(request, year, month, slug):

Even so, the decorator doesn’t provide automatic handling of OPTIONS, and organizing multiple views according to HTTP method results in simpler code, as we shall see in Chapter 9.

5.9.4 Class-Based Views Review

A CBV is simply a class that inherits View and meets the basic requirements of being a Django view: a view is a Python callable that always accepts an HttpRequest object and always returns an HttpResponse object.

The CBV organizes view behavior for a URI or set of URIs (when using named groups in a regular expression pattern) according to HTTP methods. Specifically, View is built such that it expects us to define any of the following: get(), post(), put(), patch(), delete(), trace(). We could additionally define head(), options(), but View will automatically generate these for us (for head() to be automatically generated, we must define get()).

Internally, the CBV actually steps through multiple view methods for each view. The as_view() method used in URL patterns accepts initkwargs and acts as a factory by returning an actual view called view(), which uses the initkwargs to instantiate our CBV and then calls dispatch() on the new CBV object. dispatch() selects one of the methods defined by the developer, based on the HTTP method used to request the URI. In the event that the method is undefined, the CBV raises an HTTP 405 error.

In a nutshell, as_view() is a view factory, while the combination of view(), dispatch(), and any of the developer-defined methods (get(), post(), etc.) are the actual view. Much like a function view, any of these view methods must accept an HttpRequest object, a URL dictionary, and any regular expression group data (such as slug). In turn, the full combined chain (view(), dispatch(), etc.) must return an HttpResponse object.

At first glance, CBVs are far more complex than function views. However, CBVs are more clearly organized, allow for shared behavior according to OOP, and better adhere to the rules of HTTP out of the box. We will further expand on these advantages, returning to the topic first in Chapter 9.

Our understanding of views will change in Chapter 9 and Chapter 17, but at the moment, the rule of thumb is as follows: if the view shares behavior with another view, use a CBV. If not, you have the choice between a CBV and a function view with a require_http_methods decorator, and the choice is pure preference. I personally stick with CBVs because I find the automatic addition of the HTTP OPTIONS method appealing, but many opt instead to use function views.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020