- 5.1 Introduction
- 5.2 The Purpose of Views and URL Configurations
- 5.3 Step-by-Step Examination of Django's Use of Views and URL Configurations
- 5.4 Building Tag Detail Webpage
- 5.5 Generating 404 Errors for Invalid Queries
- 5.6 Shortening the Development Process with Django View Shortcuts
- 5.7 URL Configuration Internals: Adhering to App Encapsulation
- 5.8 Implementing the Views and URL Configurations to the Rest of the Site
- 5.9 Class-Based Views
- 5.10 Redirecting the Homepage
- 5.11 Putting It All Together
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.