Since a view is a callable that takes a web request and returns a web response, you can also define your views as class methods. Django provides base view classes for this. All of them inherit from the View
class, which handles HTTP method dispatching and other functionality. This is an alternate method to create your views.
We are going to change our post_list
view into a class-based view to use the generic ListView
offered by Django. This base view allows you to list objects of any kind.
Edit the views.py
file of your blog
application and add the following code:
from django.views.generic import ListView class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 3 template_name = 'blog/post/list.html'
This class-based view is analogous to the previous post_list
view. Here, we are telling ListView
to:
queryset
attribute, we could have specified model = Post
and Django would have built the generic Post.objects.all()
queryset for us.posts
for the query results. The default variable is object_list
if we don't specify any context_object_name
.ListView
will use blog/post_list.html
.Now, open the urls.py
file of your blog
application, comment the previous post_list
URL pattern, and add a new URL pattern using the PostListView
class as follows:
urlpatterns = [ # post views # url(r'^$', views.post_list, name='post_list'), url(r'^$', views.PostListView.as_view(), name='post_list'), url(r'^(?P<year>d{4})/(?P<month>d{2})/(?P<day>d{2})/' r'(?P<post>[-w]+)/$', views.post_detail, name='post_detail'), ]
In order to keep pagination working, we have to use the right page object that is passed to the template. Django's ListView
passes the selected page in a variable called page_obj
, so you have to edit your post_list.html
template accordingly to include the paginator using the right variable, like this:
{% include "pagination.html" with page=page_obj %}
Open http://127.0.0.1:8000/blog/
in your browser and check that everything works the same way as with the previous post_list
view. This is a simple example of a class-based view that uses a generic class provided by Django. You will learn more about class-based views in Chapter 10, Building an e-Learning Platform and successive chapters.