侧边栏已经正确地显示了最新文章列表、归档、分类等信息。现在来完善归档和分类功能,当用户点击归档下的某个日期或者分类下的某个分类时,跳转到文章列表页面,显示该日期或者分类下的全部文章。
归档页面
要显示某个归档日期下的文章列表,思路和显示主页文章列表是一样的,回顾一下主页视图的代码:
blog/views.py
def index(request):
post_list = Post.objects.all().order_by('-created_time')
return render(request, 'blog/index.html', context={
'post_list': post_list})
主页视图函数中我们通过 Post.objects.all()
获取全部文章,而在我们的归档和分类视图中,我们不再使用 all
方法获取全部文章,而是使用 filter
来根据条件过滤。先来看归档视图:
blog/views.py
def archives(request, year, month):
post_list = Post.objects.filter(created_time__year=year,
created_time__month=month
).order_by('-created_time')
return render(request, 'blog/index.html', context={
'post_list': post_list})
这里我们使用了模型管理器(objects)的 filter
函数来过滤文章。由于是按照日期归档,因此这里根据文章发表的年和月来过滤。具体来说,就是根据 created_time
的 year
和