Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Django 3 By Example

You're reading from   Django 3 By Example Build powerful and reliable Python web applications from scratch

Arrow left icon
Product type Paperback
Published in Mar 2020
Publisher Packt
ISBN-13 9781838981952
Length 568 pages
Edition 3rd Edition
Languages
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Antonio Melé Antonio Melé
Author Profile Icon Antonio Melé
Antonio Melé
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Preface 1. Building a Blog Application 2. Enhancing Your Blog with Advanced Features FREE CHAPTER 3. Extending Your Blog Application 4. Building a Social Website 5. Sharing Content on Your Website 6. Tracking User Actions 7. Building an Online Shop 8. Managing Payments and Orders 9. Extending Your Shop 10. Building an E-Learning Platform 11. Rendering and Caching Content 12. Building an API 13. Building a Chat Server 14. Going Live 15. Other Books You May Enjoy
16. Index

Using class-based views

Class-based views are an alternative way to implement views as Python objects instead of functions. 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 common functionalities.

Class-based views offer advantages over function-based views for some use cases. They have the following features:

  • Organizing code related to HTTP methods, such as GET, POST, or PUT, in separate methods, instead of using conditional branching
  • Using multiple inheritance to create reusable view classes (also known as mixins)

You can take a look at an introduction to class-based views at https://docs.djangoproject.com/en/3.0/topics/class-based-views/intro/.

You will change your 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. In the preceding code, you are telling ListView to do the following things:

  • Use a specific QuerySet instead of retrieving all objects. Instead of defining a queryset attribute, you could have specified model = Post and Django would have built the generic Post.objects.all() QuerySet for you.
  • Use the context variable posts for the query results. The default variable is object_list if you don't specify any context_object_name.
  • Paginate the result, displaying three objects per page.
  • Use a custom template to render the page. If you don't set a default template, ListView will use blog/post_list.html.

Now open the urls.py file of your blog application, comment the preceding post_list URL pattern, and add a new URL pattern using the PostListView class, as follows:

urlpatterns = [
    # post views
    # path('', views.post_list, name='post_list'),
    path('', views.PostListView.as_view(), name='post_list'),
    path('<int:year>/<int:month>/<int:day>/<slug:post>/',
        views.post_detail,
        name='post_detail'),
]

In order to keep pagination working, you have to use the right page object that is passed to the template. Django's ListView generic view 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, as follows:

{% include "pagination.html" with page=page_obj %}

Open http://127.0.0.1:8000/blog/ in your browser and verify 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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime