View
class, which handles the HTTP direction method and other functions. Class-based views offer advantages over function-based views in certain cases. They have the following features: - Code associated with HTTP methods such as
GET
,POST
orPUT
in separate methods rather than condition branches. - Using inheritance to create view classes that can be used repeatedly (known as
mixins
).
Read more about class-based representations here: https://docs.djangoproject.com/en/2.0/topics/class-based-views/intro/. Let’s change the post_list
view to “class-based” to use the generic ListView
from Django. This basic view allows you to display objects of any kind. Edit the views.py
file of the 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 view is similar to the previously used post_list
. The code above tells ListView
that it should:
- Use a specific QuerySet instead of getting all objects. Instead of defining a
queryset
attribute, you can use a specificmodel = Post
, and Django will build a generic QuerySetPost.objects.all()
automatically. - Use the context variable
posts
to query results. Ifcontext_object_name
is not defined, the default variable isobject_list
. - Split the result into pages with three objects per page.
- Use a custom template for rendering. If no default template is specified,
ListView
usesblog/post_list.html
.
Now open the blog
application’s urls.py
file, comment out the previous post_list
URL pattern and add a new one using the PostListView
class:
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'),
]
For pagination to work, you need to use the correct page object that is passed to the template. The general Django ListView
view passes the selected page to the page_obj
variable, so you need to edit the post/list.html
template. This is necessary for the paginator to use the correct variable:
{% include "pagination.html" with page=page_obj %}
Open https://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 using a generic Django class.
Bottom line
You’ve learned the basics of the Django web framework and created a basic blog application. Developed data models and applied migrations. Created views, templates, and URLs for the project, including pagination. Next we’ll talk about improving the application with a comment system and tagging feature, as well as allowing users to share posts via email.