基于类的视图是将视图实现为python对象的另一种方法,而非函数。
由于视图为一种可调用的程序,接收web请求并返回web响应,因而可将视图定义为类方法。
将post_list视图修改为基于类的视图
在views.py中添加如下代码
class PostListView(ListView):
queryset = Post.published.all()
context_object_name = 'posts'
paginate_by = 3
template_name = 'blog/post/list.html'
1.使用特定的QuerySet,而不是检索全部对象;
2.若未指定context_object_name,默认变量为object_list;
修改url
path('', views.PostListView.as_view(), name='post_list'),
另外,为了保持分页机制,须使用传递至模板中的正确的页面对象。Django中通用视图ListView将页面传递至page_obj变量中,因此将posts改为page_obj
{% include "pagination.html" with page=page_obj %}