Book Image

Django 3 By Example - Third Edition

By : Antonio Melé
Book Image

Django 3 By Example - Third Edition

By: Antonio Melé

Overview of this book

If you want to learn the entire process of developing professional web applications with Python and Django, then this book is for you. In the process of building four professional Django projects, you will learn about Django 3 features, how to solve common web development problems, how to implement best practices, and how to successfully deploy your applications. In this book, you will build a blog application, a social image bookmarking website, an online shop, and an e-learning platform. Step-by-step guidance will teach you how to integrate popular technologies, enhance your applications with AJAX, create RESTful APIs, and set up a production environment for your Django projects. By the end of this book, you will have mastered Django 3 by building advanced web applications.
Table of Contents (17 chapters)
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.